This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Docs

Documentation

1 - Projects

Project tree

This tree contains projects

Requirements

  • MAY be public
  • MAY be published
  • MAY be used in builds

1.1 - Alwaldend.com

Alwaldend.com site

Features

Deployment

  • Setup dns: [infra/alwaldend.com/dns](../../infra/alwaldend.com/dns]
  • Push to the Github Pages repo:
    bazel run --config=release //projects/alwaldend.com:deploy
    

Taxonomy

Taxonomy Meaning
Categories General category
Languages Programming language
Sites Sites
Statuses Project status
Tags Generic tags

Shortcodes

alwaldend/alert

{{< alwaldend/alert >}}
Alert body
{{< /alwaldend/alert >}}

Create a link using a bazel label

Usage:

{{% alwaldend/label_link "//tools/qt" %}}

Render common links

Usage:

{{% alwaldend/links %}}

alwaldend/svg_file

Create img for an svg file

Usage:

{{< alwaldend/svg_file file=local_file.svg >}}

alwaldend/include_html

Include a local html file

Usage:

{{< alwaldend/include_html "file.html" >}}

alwaldend/docs_misc_books

Render books

Usage:

{{< alwaldend/docs_misc_books >}}

TODO

  • Setup proper deployment

1.1.1 - Releases

Releases

  • Add deploy to dockerhub, add //tools/oras
  • Remove last modification footer
  • Add missing features to the Pomodoro app, update project readmes, add github pages
  • Update infinitime patch, start adding trufflehog rules
  • Add hugo lock support, add proper hugo toolchain support, improve the ansible lock
  • Move all remaining code to main
  • Move a portion of tool code to main
  • Move the registry to //projects/bazel_registry
  • Add minisign rules
  • Remove sites taxonomy, start adding xray_manager
  • Fix release page rendering
  • Move to a light nvim theme, add full git info to releases
  • Add release_page generation, remove redundant release templates
  • Fix nvim library paths
  • Parallelize git info retrieval
  • Move links to the config, use list groups
  • Remove contracts tree
  • Add changelogs
  • Allow docs to put content outside of docs, refactor git to just use .git directly
  • Add the footer back, add hugo env information
  • Move release items to a list group, add item counter
  • Add cross-compilation, move leetcode downloader contracts out of //contracts
  • Refactor release templates into partials, add release cards
  • Add RSS links, rewrite links shortcode to html, improve release tables
  • Add file size to releases, add round_float partial
  • Write release tool in go, start adding it to projects, add py proto generation
  • Add release rules, add gzip rules, add several other tools, remove autoscrool deps from the root
  • Add dev_shell rules, add make_install_binary, flatten sh rules, add dotfiles/bin
  • Add //tools/make_install, start moving dotfiles to it
  • Add label_link shortcode, add todo page
  • Move book data to data/books
  • Add tools/rfc
  • Add bzl snippets to proto docs, add targets for ansible playbooks
  • Remove the footer from the docs
  • Add dnscontrol rules
  • Move book data to the books page, add lazy loading, save some thumbnails locally
  • Make tables more compact
  • Disable inline partials, add last modified section
  • Tweak tables again
  • Improve tables on home and books pages
  • Improve tables
  • Do not use nested tables in docs/misc/books
  • Fix book rendering, add arm CI for some reason
  • Add git image, split root MODULE.bazel
  • Add more taxonomies, remove docs tree, move alwaldend.com to projects

1.1.1.1 - head

Release head

  • Add deploy to dockerhub, add //tools/oras
  • Remove last modification footer
  • Add missing features to the Pomodoro app, update project readmes, add github pages
  • Update infinitime patch, start adding trufflehog rules
  • Add hugo lock support, add proper hugo toolchain support, improve the ansible lock
  • Move all remaining code to main
  • Move a portion of tool code to main
  • Move the registry to //projects/bazel_registry
  • Add minisign rules
  • Remove sites taxonomy, start adding xray_manager
  • Fix release page rendering
  • Move to a light nvim theme, add full git info to releases
  • Add release_page generation, remove redundant release templates
  • Fix nvim library paths
  • Parallelize git info retrieval
  • Move links to the config, use list groups
  • Remove contracts tree
  • Add changelogs
  • Allow docs to put content outside of docs, refactor git to just use .git directly
  • Add the footer back, add hugo env information
  • Move release items to a list group, add item counter
  • Add cross-compilation, move leetcode downloader contracts out of //contracts
  • Refactor release templates into partials, add release cards
  • Add RSS links, rewrite links shortcode to html, improve release tables
  • Add file size to releases, add round_float partial
  • Write release tool in go, start adding it to projects, add py proto generation
  • Add release rules, add gzip rules, add several other tools, remove autoscrool deps from the root
  • Add dev_shell rules, add make_install_binary, flatten sh rules, add dotfiles/bin
  • Add //tools/make_install, start moving dotfiles to it
  • Add label_link shortcode, add todo page
  • Move book data to data/books
  • Add tools/rfc
  • Add bzl snippets to proto docs, add targets for ansible playbooks
  • Remove the footer from the docs
  • Add dnscontrol rules
  • Move book data to the books page, add lazy loading, save some thumbnails locally
  • Make tables more compact
  • Disable inline partials, add last modified section
  • Tweak tables again
  • Improve tables on home and books pages
  • Improve tables
  • Do not use nested tables in docs/misc/books
  • Fix book rendering, add arm CI for some reason
  • Add git image, split root MODULE.bazel
  • Add more taxonomies, remove docs tree, move alwaldend.com to projects

1.2 - Android launcher

Android launcher

Features

  • Android app
  • Kotlin, Jetpack Compose
  • Only text
  • FOSS, no ads, no internet access, no tracking, minimal dependencies
  • Allows you to hide apps

1.2.1 - Releases

Releases

  • Add deploy to dockerhub, add //tools/oras
  • Add missing features to the Pomodoro app, update project readmes, add github pages
  • Move all remaining code to main
  • Add release_page generation, remove redundant release templates
  • Add //tools/bazelrc, move to a bazelrc preset
  • Remove contracts tree
  • Allow docs to put content outside of docs, refactor git to just use .git directly
  • Add cross-compilation, move leetcode downloader contracts out of //contracts
  • Refactor release templates into partials, add release cards
  • Add more taxonomies, remove docs tree, move alwaldend.com to projects
  • Rename proto to contracts, add tools/proto add proto docs
  • Remove bazel target docs, add tools/docs, tag projects properly
  • Improve doc structure
  • Remove changelogs, ignore irrelevant directories in docs
  • Move another group of rules to tools/
  • Move a group of rules to tools/
  • Remove kt tree

  • release_deps.dot
  • launcher_binary_unsigned.apk
  • launcher_binary.apk

1.2.1.1 - head

Release head

  • Add deploy to dockerhub, add //tools/oras
  • Add missing features to the Pomodoro app, update project readmes, add github pages
  • Move all remaining code to main
  • Add release_page generation, remove redundant release templates
  • Add //tools/bazelrc, move to a bazelrc preset
  • Remove contracts tree
  • Allow docs to put content outside of docs, refactor git to just use .git directly
  • Add cross-compilation, move leetcode downloader contracts out of //contracts
  • Refactor release templates into partials, add release cards
  • Add more taxonomies, remove docs tree, move alwaldend.com to projects
  • Rename proto to contracts, add tools/proto add proto docs
  • Remove bazel target docs, add tools/docs, tag projects properly
  • Improve doc structure
  • Remove changelogs, ignore irrelevant directories in docs
  • Move another group of rules to tools/
  • Move a group of rules to tools/
  • Remove kt tree

  • release_deps.dot
  • launcher_binary_unsigned.apk
  • launcher_binary.apk

1.3 - Ansible collection

Ansible collection alwaldend.main

Features

  • Ansible collection

Galaxy

namespace: alwaldend
name: main
version: 0.0.0
readme: README.md
authors:
-  <example@domain.com>
description: main alwaldend ansible collection
license:
  - AGPL-3.0-or-later
license_file: LICENSE.txt
tags: []
dependencies:
  ansible.posix: 1.5.4
  community.crypto: 2.17.0
  community.general: 8.2.0
  devsec.hardening: 9.0.1
  community.docker: 3.11.0
repository: https://git.alwaldend.com/src
documentation: https://collection-main.docs.alwaldend.com
homepage: https://collection-main.docs.alwaldend.com
issues: ""
build_ignore: []

1.3.1 - Playbooks

Ansible playbooks

1.3.2 - Roles

Ansible roles

1.3.2.1 - Adguard

Role to deploy adguard

1.3.2.1.1 - Defaults

Defaults for adguard
adguard_dir: /etc/adguard
adguard_work_dir: "{{ adguard_dir }}"
adguard_gpg_key_url: https://keys.openpgp.org/vks/v1/by-fingerprint/28645AC9776EC4C00BCE2AFC0FE641E7235E2EC6
adguard_gpg_key_src: files/key.asc
adguard_gpg_key_path: "{{ adguard_dir }}/release-key.asc"
adguard_gpg_key_checksum: "22d78dbacb461667861ee7d2dd13d13240ee003d"
adguard_release_source_url: https://github.com/AdguardTeam/AdGuardHome/releases/download
adguard_release_version: v0.107.48
adguard_release_checksum: "sha512:c0a336212e3792ae6fc6b8de976befce0038c5d6ddde919a00994c43a929349958c7bd65f7fb7fdd471962afa20855ecbf5830cc7a1d26f3037a716db638c101"
adguard_release_distrib: AdGuardHome_linux_amd64.tar.gz
adguard_release_url: "{{ adguard_release_source_url }}/{{ adguard_release_version }}/{{ adguard_release_distrib }}"
adguard_release_archive_dest: "{{ adguard_dir }}/release-{{ adguard_release_version }}-{{ adguard_release_distrib }}" 
adguard_release_dest: "{{ adguard_dir }}/release-{{ adguard_release_version }}" 
adguard_release_dir: "{{ adguard_release_dest }}/AdGuardHome"
adguard_release_bin: "{{ adguard_release_dir }}/AdGuardHome"
adguard_release_sig: "{{ adguard_release_bin }}.sig"

1.3.2.2 - Caddy

Role to deploy caddy

1.3.2.2.1 - Defaults

Defaults for caddy
caddy_enabled: false
caddy_user: caddy
caddy_config_path: /etc/caddy/Caddyfile
caddy_config_dir: /etc/caddy/configs
caddy_config: |
  import {{ caddy_config_dir }}/*

1.3.2.3 - CIFS

Setup cifs

1.3.2.3.1 - Defaults

Defaults for cifs
cifs_enabled: false
cifs_systemd_dir: /etc/systemd/system
cifs_mounts: []

1.3.2.4 - Consul

Setup consul

1.3.2.4.1 - Defaults

Defaults for consul
consul_is_server: false
consul_user_name: consul
consul_user_uid:
consul_dir: "/opt/consul"
consul_persistence_dir: "{{ consul_dir }}"
consul_releases_dir: "{{ consul_dir }}/releases"
consul_config_symlink_dir: "{{ consul_configs_dir }}/current"
consul_config_symlink_data_dir: "{{ consul_config_symlink_dir }}/configs"
consul_configs_dir: "{{ consul_persistence_dir }}/configs/{{ inventory_hostname }}"
consul_data_dir: "{{ consul_persistence_dir }}/data/{{ inventory_hostname }}"
consul_config_path: "{{ consul_config_config_dir }}/consul.json"
consul_config_dir: "{{ consul_configs_dir }}/{{ consul_config_dir_name }}" 
consul_config_data_dir: "{{ consul_config_dir }}/data"
consul_config_config_dir: "{{ consul_config_dir }}/configs"
consul_config_dir_name: "{{ consul_config_version }}"
consul_config_version: "{{ lookup('ansible.builtin.pipe', 'git rev-parse HEAD') }}"
consul_env: {}
consul_configs: []
consul_env_path: "{{ consul_config_data_dir }}/consul.env"
consul_env_symlink_path: "{{ consul_config_symlink_dir }}/data/consul.env"
consul_release_dir: "{{ consul_releases_dir }}/{{ consul_release_dir_name }}"
consul_release_dir_name: "{{ consul_release_version }}"
consul_release_symlink_path: "{{ consul_releases_dir }}/current"
consul_release_symlink_bin_path: "{{ consul_release_symlink_path }}/consul"
consul_release_version: 1.20.2
consul_release_archive_name: "consul_{{ consul_release_version }}_linux_amd64"
consul_release_archive_fullname: "{{ consul_release_archive_name }}.zip"
consul_release_bin_path: "{{ consul_release_dir }}/consul"
consul_release_url: "https://releases.hashicorp.com/consul/{{ consul_release_version }}/{{ consul_release_archive_fullname }}"
consul_release_checksum: "sha256:1bf7ddf332f02e6e36082b0fdf6c3e8ce12a391e7ec7dafd3237bb12766a7fd5"
consul_agent_ca_cert_path: "{{ consul_config_data_dir }}/agent_ca_cert.pub"
consul_agent_ca_cert:
consul_server_cert_path: "{{ consul_config_data_dir }}/server_cert_{{ inventory_hostname }}.pub"
consul_server_cert:
consul_server_key_path: "{{ consul_config_data_dir }}/server_cert_{{ inventory_hostname }}.key"
consul_server_key:

1.3.2.5 - Consul envoy

Setup envoy for consul

1.3.2.5.1 - Defaults

Defaults for consul_envoy
consul_envoy_dir: "/opt/consul_envoy"
consul_envoy_deployments_dir: "{{ consul_envoy_dir }}/deployments"
consul_envoy_releases_dir: "{{ consul_envoy_dir }}/releases"
consul_envoy_deployment_dir: "{{ consul_envoy_deployments_dir }}/{{ consul_envoy_deployment_version }}"
consul_envoy_release_dir: "{{ consul_envoy_releases_dir }}/{{ consul_envoy_release_version }}"
consul_envoy_configs_dir: "{{ consul_envoy_deployment_dir }}/configs"
consul_envoy_bootstrap_config_path: "{{ consul_envoy_configs_dir }}/bootstrap.json"
consul_envoy_deployment_version: "{{ lookup('ansible.builtin.pipe', 'git rev-parse HEAD') }}"
consul_envoy_user_name: consul_envoy
consul_envoy_release_version: 1.31.0
consul_envoy_release_archive_fullname: "envoy_{{ consul_envoy_release_version }}_linux_amd64.zip"
consul_envoy_release_url: "https://releases.hashicorp.com/envoy/{{ consul_envoy_release_version }}/{{ consul_envoy_release_archive_fullname }}"
consul_envoy_release_bin_path: "{{ consul_envoy_release_dir }}/envoy"
consul_envoy_release_symlink_path: "{{ consul_envoy_releases_dir }}/current"
consul_envoy_release_checksum: "sha256:350782275de0fe50699844b4f9096d77a0193a5bcf205e14b8ad964ec429d45e"

1.3.2.6 - DNS

Setup dns records

1.3.2.6.1 - Defaults

Defaults for dns
dns_records: []
dns_domains: []
dns_njalla_api_url: https://njal.la/api/1/
dns_njalla_token:

1.3.2.7 - Docker

Setup docker

1.3.2.7.1 - Defaults

Defaults for docker
docker_enabled: false

1.3.2.8 - Facts

Setup ansible facts

1.3.2.8.1 - Defaults

Defaults for facts

1.3.2.9 - Firewall

Setup firewall

1.3.2.9.1 - Defaults

Defaults for firewall
firewall_state: enabled
firewall_enabled: true
firewall_allow_port_from: []

1.3.2.10 - Hiddify manager

Setup hiddify manager

1.3.2.10.1 - Defaults

Defaults for hiddify_manager
hiddify_manager_env:
  HIDDIFY_MANAGER_IMAGE: ghcr.io/hiddify/hiddify-manager:main@sha256:d5edef06d2133ffa26f0fcbb67e711f4356dba44c44a41a96570c4e03845a84c
  HIDDIFY_MANAGER_REDIS_IMAGE: redis:7.4.1@sha256:bb142a9c18ac18a16713c1491d779697b4e107c22a97266616099d288237ef47
  HIDDIFY_MANAGER_MARIADB_IMAGE: mariadb:11.6.2@sha256:a9547599cd87d7242435aea6fda22a9d83e2c06d16c658ef70d2868b3d3f6a80
  HIDDIFY_MANAGER_REDIS_PASSWORD: "{{ lookup('ansible.builtin.env', 'HIDDIFY_MANAGER_REDIS_PASSWORD') | mandatory('HIDDIFY_MANAGER_REDIS_PASSWORD') }}"
  HIDDIFY_MANAGER_MYSQL_PASSWORD: "{{ lookup('ansible.builtin.env', 'HIDDIFY_MANAGER_MYSQL_PASSWORD') | mandatory('HIDDIFY_MANAGER_MYSQL_PASSWORD') }}"
  HIDDIFY_MANAGER_MARIADB_PASSWORD: "{{ lookup('ansible.builtin.env', 'HIDDIFY_MANAGER_MARIADB_PASSWORD') | mandatory('HIDDIFY_MANAGER_MARIADB_PASSWORD') }}"
hiddify_manager_env_override: {}
hiddify_manager_dir: /opt/hiddify_manager

1.3.2.11 - Hiddify manager with host

Setup host and then hiddify manager

1.3.2.11.1 - Defaults

Defaults for hiddify_manager_host

1.3.2.12 - Host

Common host setup

1.3.2.12.1 - Defaults

Defaults for host

1.3.2.13 - K3s

Setup k3s

1.3.2.13.1 - Defaults

Defaults for k3s
k3s_install_environment: {}
k3s_manifests_dir: /var/lib/rancher/k3s/server/manifests
k3s_install_script_path: /usr/local/bin/k3s_install.sh
k3s_config_path: /etc/rancher/k3s/config.yaml
k3s_config: {}
k3s_service_name: k3s

1.3.2.14 - K3s bootstrap

Bootstrap k3s cluster

1.3.2.14.1 - Defaults

Defaults for k3s_bootstrap
k3s_bootstrap_apply_path: 
k3s_bootstrap_token_name: "{{ lookup('ansible.builtin.env', 'USER') }}"
k3s_bootstrap_token_namespace: kube-system
k3s_bootstrap_venv_dir: "/opt/bootstrap-venv"
k3s_bootstrap_venv_bin: "{{ k3s_bootstrap_venv_dir | mandatory }}/bin/python"
k3s_bootstrap_kubeconfig: /etc/rancher/k3s/k3s.yaml
k3s_bootstrap_cluster_name: "{{ inventory_hostname }}"
k3s_bootstrap_cluster_ca_path: "{{ lookup('ansible.builtin.env', 'HOME') | mandatory }}/.kube/ca-{{ k3s_bootstrap_cluster_name | mandatory }}.ca.crt"
k3s_bootstrap_user_ca_path: "{{ k3s_bootstrap_cluster_ca_path | mandatory | dirname }}/ca-{{ k3s_bootstrap_cluster_name | mandatory }}-{{ k3s_bootstrap_token_name | mandatory }}.ca.crt"
k3s_bootstrap_user_name: "{{ k3s_bootstrap_cluster_name | mandatory }}-{{ k3s_bootstrap_token_name | mandatory }}" 
k3s_bootstrap_cluster_port: 

1.3.2.15 - K3s cluster

Setup k3s cluster

1.3.2.15.1 - Defaults

Defaults for k3s_cluster

1.3.2.16 - OS

Common os setup

1.3.2.16.1 - Defaults

Defaults for os
os_hardening_enabled: true

1.3.2.17 - PVE cluster

Setup PVE cluster

1.3.2.17.1 - Defaults

Defaults for pve_cluster
pve_cluster_remove_repos:
  - pve-enterprise.list 
  - ceph.list
pve_cluster_add_repos:
  - name: pve-no-subscription
    value: deb http://download.proxmox.com/debian/pve bookworm pve-no-subscription
  - name: ceph-squid
    value: deb http://download.proxmox.com/debian/ceph-squid bookworm no-subscription
pve_cluster_node_config: []
pve_cluster_admins: []
pve_cluster_cluster_name:
pve_cluster_acme_accounts: []
pve_cluster_acme_plugins: []
pve_cluster_venv_dir: /opt/ansible/pve_cluster_venv
pve_cluster_venv_packages: 
  - pexpect
pve_cluster_base_image_dir: /var/lib/vz/template
pve_cluster_node_name: "{{ inventory_hostname | mandatory | split('.') | first }}"
pve_cluster_ceph_enabled: false
pve_cluster_ceph_repository: no-subscription
pve_cluster_ceph_osd: []
pve_cluster_ceph_pools: []
pve_cluster_ceph_mon: []
pve_cluster_ceph_mgr: []
pve_cluster_ceph_mds: []
pve_cluster_storages: []
pve_cluster_storage_config_path: /etc/pve/storage.cfg

1.3.2.18 - PVE VM

Setup PVE VM

1.3.2.18.1 - Defaults

Defaults for pve_vm
pve_vm_agent: 
pve_vm_name: "{{ inventory_hostname }}"
pve_vm_delegate_update_known_hosts: localhost
pve_vm_delegate_pve: 
pve_vm_set: "{{ pve_vm_set_default + pve_vm_set_additional }}"
pve_vm_set_default: []
pve_vm_set_additional: []
pve_vm_set_creation: "{{ pve_vm_set_creation_default + pve_vm_set_creation_additional }}"
pve_vm_set_creation_default: []
pve_vm_set_creation_additional: []
pve_vm_resize: []
pve_vm_venv_dir: "/opt/ansible/pve_vm_venv"
pve_vm_init_user:
pve_vm_venv_packages:
  - proxmoxer
  - requests

1.3.2.19 - PVE VM remove

Remove PVE VM

1.3.2.19.1 - Defaults

Defaults for pve_vm_remove

1.3.2.20 - Raspberry pi

Setup raspberry pi

1.3.2.20.1 - Defaults

Defaults for raspberry_pi
raspberry_pi_argon_enabled: false
raspberry_pi_containers_enabled: false
raspberry_pi_argon_eeprom_script_path: /usr/local/bin/argon_argon_eeprom.sh
raspberry_pi_argon_argon1_script_path: /usr/local/bin/argon_argon1.sh
raspberry_pi_cmdline_path: /boot/firmware/cmdline.txt

1.3.2.21 - SSH

Setup ssh

1.3.2.21.1 - Defaults

Defaults for ssh
ssh_hardening_enabled: true

1.3.2.22 - SSH port forwarding

Setup SSH port forwarding

1.3.2.22.1 - Defaults

Defaults for ssh_port_forward
ssh_port_forward_local_addr: 127.0.0.1
ssh_port_forward_script_path: /usr/local/bin/ssh-port-forward

1.3.2.23 - SSH update known hosts

Update known hosts

1.3.2.23.1 - Defaults

Defaults for ssh_update_known_hosts
ssh_update_known_hosts_hosts: []

1.3.2.24 - Traefik

Setup traefik

1.3.2.24.1 - Defaults

Defaults for traefik
traefik_user: traefik
traefik_user_uid: 3653
traefik_env: {}
traefik_data_dir: /mnt/traefik
traefik_log_dir: "/var/log/traefik"
traefik_certificates_dir: "{{ traefik_data_dir }}/certificates"
traefik_configs_dir: "{{ traefik_data_dir }}/configs"
traefik_configs_version: "{{ lookup('ansible.builtin.pipe', 'git rev-parse HEAD') }}"
traefik_configs_dynamic_dir: "{{ traefik_configs_cur_dir }}/dynamic"
traefik_configs_dynamic_dir_symlink: "{{ traefik_configs_symlink }}/dynamic"
traefik_configs_cur_dir_name: "{{ traefik_configs_version }}"
traefik_configs_cur_dir: "{{ traefik_configs_dir }}/{{ traefik_configs_cur_dir_name }}"
traefik_configs_symlink: "{{ traefik_configs_dir }}/current"
traefik_static_config_path: "{{ traefik_configs_symlink }}/traefik.yaml"
traefik_releases_dir: /opt/traefik/releases
traefik_static_config:
traefik_dynamic_configs: []
traefik_release_version: v3.3.1 
traefik_release_dir_name: "{{ traefik_release_version }}"
traefik_release_dir: "{{ traefik_releases_dir }}/{{ traefik_release_dir_name }}"
traefik_release_symlink: "{{ traefik_releases_dir }}/current"
traefik_release_symlink_bin: "{{ traefik_release_symlink }}/traefik"
traefik_release_archive_name: "traefik_{{ traefik_release_version }}_linux_amd64"
traefik_release_archive_full: "traefik_{{ traefik_release_version }}_linux_amd64.tar.gz"
traefik_release_bin_path: "{{ traefik_release_dir }}/traefik"
traefik_release_download_url: "https://github.com/traefik/traefik/releases/download/{{ traefik_release_version }}/{{ traefik_release_archive_full }}"
traefik_release_download_checksum: sha256:27fd502a8d80fc81b97faf5cebd7a1cbc1a2c5369d18e0f4471a66d1a8c139ce

1.3.2.25 - Update all packages

Update all system packages

1.3.2.25.1 - Defaults

Defaults for update_all_packages

1.3.2.26 - Users

Setup system users

1.3.2.26.1 - Defaults

Defaults for users
users_regular: {}
users_remove: {}
users_admins:
  ansible:
    name: ansible
    disable_passwd: true
    sudo_no_passwd: true
users_ssh_keys:
  ansible:
    user: ansible
    key: ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMQT6QEqCFlQDRNaU+RrZ0VYoULYttA6oxjJ5U5h75

1.3.2.27 - Vault

Setup Hashicorp Vault

1.3.2.27.1 - Defaults

Defaults for vault
vault_data_driver_opts:
vault_traefik_static_config:
vault_traefik_dynamic_configs: []
vault_openbao_config:
vault_openbao_image: docker.io/openbao/openbao:2.1@sha256:7de07aa6df3937d44c96c2d65c188b2d4a70546f2a764ad4510301305af6a223
vault_traefik_image: docker.io/traefik:v3.3@sha256:bc534d72121b187efc3706780d604b2a6590ef321c441ef137289052633d27d4
vault_user: vault
vault_user_uid: 3123
vault_env: {}
vault_dir: /opt/vault

1.3.2.28 - Wireguard

Setup wireguard

1.3.2.28.1 - Defaults

Defaults for wireguard
wireguard_enabled: false
wireguard_configs: []
wireguard_dir: "/etc/wireguard"

1.3.2.29 - Xray

Setup xray

Links:

1.3.2.29.1 - Defaults

Defaults for xray
xray_enabled: false
xray_config_dir: /usr/local/etc/xray
xray_log_dir: /var/log/xray
xray_config_path: "{{ xray_config_dir }}/0-main.json"
xray_client_id:
xray_wireguard_relays: []
xray_wireguard_ipv4_address:
xray_wireguard_ipv6_address:
xray_wireguard_private_key:
xray_config:
xray_configs: {}
xray_user: xray
xray_socket_dir: /var/shm/xray
xray_caddy_config_path: /etc/caddy/configs/xray.Caddyfile
xray_subscriptions_dir: /usr/local/etc/xray-subscriptions
xray_caddy_user: caddy

1.4 - Autoscroll

CLI app for autoscroll

Features

  • Platfrom-independent autoscroll
  • Config file with hot-reload
  • Some argparse tinkering
  • Python3, PyQt6

Usage

By default, the icon is disabled, to enable it pass --icon-enable

You can pass file contents as command line arguments using @path/to/the/file syntax. Arguments in that case can be placed wherever - on one line, on several lines

If you want to dynamically pass runtime arguments (without restarting the process), you can use --config options for it

Once you press --buttons-start, you can scroll vertically or horizontally just by moving your mouse untill you press --buttons-end

If --buttons-hold is set, the srolling ends once you release --buttons-start

Once --buttons-start is pressed, the scroll thread starts looping Every loop consists of sleeping for an interval, then scrolling for either 0, 1, or -1 pixels on both axis towards the starting point Starting point is the point where --buttons-start was pressed Sleep interval is recalculated on every mouse move as such:

    100 / (--scrolling-acceleration * max(distance) + --scrolling-speed)

If --scrolling-acceleration is not 0, the speed of scrolling will be faster the farther away you are from the starting point If --scrolling-acceleration is 0, the speed of scrolling will be constant

Examples

Use the package

python3 -m venv venv
. venv/bin/activate
pip install autoscroll
autoscroll

Command line options

autoscroll --buttons-start 1 --debug-click --icon-disable

Pass a configuration file once

autoscroll --icon-enable @config.txt

If config.txt is defined like this, its contents will be used as command line arguments - they will be loaded only once Arguments can be placed wherever - on one line, on several lines For example,

--buttons-start 1
--buttons-hold --debug-click

Listen for changes in the configuration file

autoscroll --config-enable --config-path config.txt

If config.txt is defined like this, the process will listen for changes in that file and update itself Arguments can be placed wherever - on one line, on several lines The file is checked for changess every --config-interval For example:

--buttons-start 1 --buttons-hold
--debug_click

--help output

usage: autoscroll [-h] [-ss SCROLLING_SPEED] [-sd SCROLLING_DEAD_AREA]
                  [-sa SCROLLING_ACCELERATION] [-bh] [-bs BUTTONS_START] [-be BUTTONS_END]
                  [-ce] [-cp CONFIG_PATH] [-ci CONFIG_INTERVAL] [-ie] [-ip ICON_PATH]
                  [-is ICON_SIZE] [-df] [-dc] [-ds] [-di]

...

options:
  -h, --help            show this help message and exit

scrolling:

  -ss, --scrolling-speed int
                        constant part of the scrolling speed
                        [default: 300]
  -sd, --scrolling-dead-area int
                        size of the square area aroung the starting point where scrolling will stop, in
                        pixels
                        [default: 50]
  -sa, --scrolling-acceleration int
                        dynamic part of the scrolling speed, depends on the distance from the point
                        where the scrolling started, can be set to 0
                        [default: 10]

buttons:

  -bh, --buttons-hold   if set, the scrolling will end once you release --buttons-start
  -bs, --buttons-start int
                        button that starts the scrolling
                        [default: 2]
  -be, --buttons-end int
                        button that ends the scrolling
                        [default: --buttons-start]

config:

  -ce, --config-enable  if set, arguments from the configuration file on --config-path will be loaded
                        every --config-interval
  -cp, --config-path str
                        path to the configuration file
                        [default: ~/.config/autoscroll/config.txt]
  -ci, --config-interval int
                        how often the config file should be checked for changes, in seconds
                        [default: 5]

icon:

  -ie, --icon-enable    if set, the icon will be enabled
  -ip, --icon-path str  path to the icon
                        [default: resources/img/icon.svg]
  -is, --icon-size int  size of the icon, in pixels
                        [default: 30]

debug:

  -df, --debug-file     if set, every time the config file is parsed, information will be printed to
                        stdout
  -dc, --debug-click    if set, click info will be printed to stdout
  -ds, --debug-scroll   if set, scroll info will be printed to stdout
  -di, --debug-initial  if set, startup configuration will be printed to stdout

1.4.1 - Releases

Releases

  • Add deploy to dockerhub, add //tools/oras
  • Add missing features to the Pomodoro app, update project readmes, add github pages
  • Move all remaining code to main
  • Move a portion of tool code to main
  • Use separate lock files for each golang tool
  • Add release_page generation, remove redundant release templates
  • Allow docs to put content outside of docs, refactor git to just use .git directly
  • Add cross-compilation, move leetcode downloader contracts out of //contracts
  • Refactor release templates into partials, add release cards
  • Write release tool in go, start adding it to projects, add py proto generation
  • Add release rules, add gzip rules, add several other tools, remove autoscrool deps from the root
  • Flatten third_party, split tools/bzl a bit
  • Add more taxonomies, remove docs tree, move alwaldend.com to projects
  • Remove bazel target docs, add tools/docs, tag projects properly
  • Remove changelogs, ignore irrelevant directories in docs
  • Remove patch tree, remove py tree

  • release_deps.dot
  • autoscroll-0.0.0-py3-none-any.whl

1.4.1.1 - head

Release head

  • Add deploy to dockerhub, add //tools/oras
  • Add missing features to the Pomodoro app, update project readmes, add github pages
  • Move all remaining code to main
  • Move a portion of tool code to main
  • Use separate lock files for each golang tool
  • Add release_page generation, remove redundant release templates
  • Allow docs to put content outside of docs, refactor git to just use .git directly
  • Add cross-compilation, move leetcode downloader contracts out of //contracts
  • Refactor release templates into partials, add release cards
  • Write release tool in go, start adding it to projects, add py proto generation
  • Add release rules, add gzip rules, add several other tools, remove autoscrool deps from the root
  • Flatten third_party, split tools/bzl a bit
  • Add more taxonomies, remove docs tree, move alwaldend.com to projects
  • Remove bazel target docs, add tools/docs, tag projects properly
  • Remove changelogs, ignore irrelevant directories in docs
  • Remove patch tree, remove py tree

  • release_deps.dot
  • autoscroll-0.0.0-py3-none-any.whl

1.5 - Bazel registry

Custom bazel registry

Features

  • Custom Bazel registry

1.5.1 - Bzl

Bazel code

1.5.1.1 - al_bzl_registry_docs

al_bzl_registry_docs

load("@com_alwaldend_src//projects/bazel_registry/main/bzl:al_bzl_registry_docs.bzl", "al_bzl_registry_docs")

al_bzl_registry_docs(name, srcs, visibility)

Create bazel registry docs

PARAMETERS

Name Description Default Value
name name none
srcs registry sources none
visibility visibility None

1.5.2 - Registry

Bazel registry

1.5.2.1 - com_github_georgewfraser_java_language_server

Module com_github_georgewfraser_java_language_server

Usage

bazel_dep(name = "com_github_georgewfraser_java_language_server", version = "2025.520.0")

Metadata

homepagehttps://github.com/georgewfraser/java-language-server
maintainers
    repository
    • github:georgewfraser/java-language-server
    versions
    • 2025.520.0
    yanked_versions

    1.5.2.1.1 - 2025.520.0

    Version 2025.520.0 of module com_github_georgewfraser_java_language_server

    Usage

    bazel_dep(name = "com_github_georgewfraser_java_language_server", version = "2025.520.0")
    

    Source

    integritysha256-Jdsud6bH3REoFNPH37slFkoR35hCt9M5r70t2yiplc8=
    overlay
    strip_prefixjava-language-server-0f4eda83443a34f92f3ad4b7cf7384fe69fbbbff
    urlhttps://github.com/georgewfraser/java-language-server/archive/0f4eda83443a34f92f3ad4b7cf7384fe69fbbbff.zip

    1.5.2.2 - org_openssl_openssl

    Module org_openssl_openssl

    Usage

    bazel_dep(name = "org_openssl_openssl", version = "3.5.0")
    

    Metadata

    homepagehttps://www.openssl.org
    maintainers
      repository
      • github:openssl/openssl
      versions
      • 3.5.0
      yanked_versions

      1.5.2.2.1 - 3.5.0

      Version 3.5.0 of module org_openssl_openssl

      Usage

      bazel_dep(name = "org_openssl_openssl", version = "3.5.0")
      

      Source

      integritysha256-NE0KefGpsIApsHROLMQBpD+ckKzRBE0JpTC0iFqOn8A=
      overlay
      BUILD.bazelsha256-dtkqThugXGWTranlWAfAUpWguKgVV50IoHaYvjhV750=
      strip_prefixopenssl-3.5.0
      urlhttps://github.com/openssl/openssl/releases/download/openssl-3.5.0/openssl-3.5.0.tar.gz

      1.5.2.3 - us_nasm_nasm

      Module us_nasm_nasm

      Usage

      bazel_dep(name = "us_nasm_nasm", version = "2.15.05")
      

      Metadata

      homepagehttps://www.nasm.us
      maintainers
        repository
        • https://www.nasm.us
        versions
        • 2.15.05
        yanked_versions

        1.5.2.3.1 - 2.15.05

        Version 2.15.05 of module us_nasm_nasm

        Usage

        bazel_dep(name = "us_nasm_nasm", version = "2.15.05")
        

        Source

        integritysha256-9ck8FG9StPFmT6POZXn5YakQ6GmrDa5DG9hxvdJYTvI=
        mirror_urls
        • https://www.nasm.us/pub/nasm/releasebuilds/2.15.05/win64/nasm-2.15.05-win64.zip
        overlay
        BUILD.bazelsha256-RbiSkFGjHVWJyU+XoMxBg/NK+tlIGjPypMxLZnDTzBI=
        strip_prefixnasm-2.15.05
        urlhttps://mirror.bazel.build/www.nasm.us/pub/nasm/releasebuilds/2.15.05/win64/nasm-2.15.05-win64.zip

        1.6 - Ci platform

        Ci platform

        TODO

        • Migrate the code to Bazel

        1.7 - Dotfiles

        Dotfiles

        Features

        • Archive with dotfiles that can be installed using make

        Bazel usage

        bazel run //projects/dotfiles:help # Show help
        bazel run //projects/dotfiles:diff # Show diff
        bazel run //projects/dotfiles:install # Install files
        

        Archive usage

        oras pull --output "${PWD}" docker.io/alwaldend/src:projects_dotfiles_dotfiles_tar_head
        cd releases/projects/dotfiles/head/files
        tar -xf dotfiles.tar
        cd dotfiles
        make help # Show help
        make diff # Check diff between system files and those from the archive
        make diff/nvim # Check diff for all nvim files
        make diff/nvim/.config/nvim/lazy-lock.json # Diff specific file
        make install # Install all files from the archive
        make install/nvim # Install nvim files
        make install/nvim/.config/nvim/lazy-lock.json # Install a specific file
        

        Help

        help: Show help
        install: Install files from the archive
        diff: Show diff between archive files and system files
        install/bin: Install bin files
        diff/bin: Diff bin files
        install/home: Install home files
        diff/home: Diff home files
        install/nvim: Install nvim files
        diff/nvim: Diff nvim files
        make: Nothing to be done for 'help'.
        

        1.7.1 - Releases

        Releases

        • Add deploy to dockerhub, add //tools/oras
        • Add missing features to the Pomodoro app, update project readmes, add github pages
        • Move all remaining code to main
        • Move a portion of tool code to main
        • Switch to a dark theme, add cname for rancher
        • Fix release page rendering
        • Fix lsp config, fix JAVA_HOME
        • Move to a light nvim theme, add full git info to releases
        • Add release_page generation, remove redundant release templates
        • Add //tools/bazelrc, move to a bazelrc preset
        • Fix nvim library paths
        • Allow docs to put content outside of docs, refactor git to just use .git directly
        • Add cross-compilation, move leetcode downloader contracts out of //contracts
        • Refactor release templates into partials, add release cards
        • Add RSS links, rewrite links shortcode to html, improve release tables
        • Add file size to releases, add round_float partial
        • Write release tool in go, start adding it to projects, add py proto generation
        • Add release rules, add gzip rules, add several other tools, remove autoscrool deps from the root
        • Refactor dev_shell into bzlenv, add deactivation, make it functional
        • Add dev_shell rules, add make_install_binary, flatten sh rules, add dotfiles/bin
        • Make functional make_install archive
        • Add //tools/make_install, start moving dotfiles to it
        • Add more taxonomies, remove docs tree, move alwaldend.com to projects
        • Remove bazel target docs, add tools/docs, tag projects properly
        • Remove cfg tree, add projects/dotfiles

        • release_deps.dot
        • dotfiles.tar
        • adguard-server.json
        • cookie-auto-delete-core-settings.json
        • ergohaven_hpd.json
        • ergohaven_hpd_v2.json
        • ergohaven_k02.json
        • ergohaven_k03.json
        • ergohaven_k03_v3.json

        1.7.1.1 - head

        Release head

        • Add deploy to dockerhub, add //tools/oras
        • Add missing features to the Pomodoro app, update project readmes, add github pages
        • Move all remaining code to main
        • Move a portion of tool code to main
        • Switch to a dark theme, add cname for rancher
        • Fix release page rendering
        • Fix lsp config, fix JAVA_HOME
        • Move to a light nvim theme, add full git info to releases
        • Add release_page generation, remove redundant release templates
        • Add //tools/bazelrc, move to a bazelrc preset
        • Fix nvim library paths
        • Allow docs to put content outside of docs, refactor git to just use .git directly
        • Add cross-compilation, move leetcode downloader contracts out of //contracts
        • Refactor release templates into partials, add release cards
        • Add RSS links, rewrite links shortcode to html, improve release tables
        • Add file size to releases, add round_float partial
        • Write release tool in go, start adding it to projects, add py proto generation
        • Add release rules, add gzip rules, add several other tools, remove autoscrool deps from the root
        • Refactor dev_shell into bzlenv, add deactivation, make it functional
        • Add dev_shell rules, add make_install_binary, flatten sh rules, add dotfiles/bin
        • Make functional make_install archive
        • Add //tools/make_install, start moving dotfiles to it
        • Add more taxonomies, remove docs tree, move alwaldend.com to projects
        • Remove bazel target docs, add tools/docs, tag projects properly
        • Remove cfg tree, add projects/dotfiles

        • release_deps.dot
        • dotfiles.tar
        • adguard-server.json
        • cookie-auto-delete-core-settings.json
        • ergohaven_hpd.json
        • ergohaven_hpd_v2.json
        • ergohaven_k02.json
        • ergohaven_k03.json
        • ergohaven_k03_v3.json

        1.8 - Infinitime

        Fork of InfiniTimeOrg/InfiniTime

        Features

        • Extra Watchface: Text
        • Extra app: Pomodoro
        • C++, embedded

        1.8.1 - Releases

        Releases

        • Add deploy to dockerhub, add //tools/oras
        • Add missing features to the Pomodoro app, update project readmes, add github pages
        • Update infinitime patch, start adding trufflehog rules
        • Move all remaining code to main
        • Add disk cache, fix infinitime build, add infinitime release
        • Build infinitime in a separate repository
        • Start refactoring the infinitime build
        • Add more taxonomies, remove docs tree, move alwaldend.com to projects
        • Remove bazel target docs, add tools/docs, tag projects properly
        • Remove changelogs, ignore irrelevant directories in docs
        • Remove bzl tree
        • Move another group of rules to tools/
        • Move a group of rules to tools/
        • Remove c and cpp trees

        • release_deps.dot
        • patches.tar
        • pinetime-mcuboot-app-dfu-1.15.0.zip

        1.8.1.1 - head

        Release head

        • Add deploy to dockerhub, add //tools/oras
        • Add missing features to the Pomodoro app, update project readmes, add github pages
        • Update infinitime patch, start adding trufflehog rules
        • Move all remaining code to main
        • Add disk cache, fix infinitime build, add infinitime release
        • Build infinitime in a separate repository
        • Start refactoring the infinitime build
        • Add more taxonomies, remove docs tree, move alwaldend.com to projects
        • Remove bazel target docs, add tools/docs, tag projects properly
        • Remove changelogs, ignore irrelevant directories in docs
        • Remove bzl tree
        • Move another group of rules to tools/
        • Move a group of rules to tools/
        • Remove c and cpp trees

        • release_deps.dot
        • patches.tar
        • pinetime-mcuboot-app-dfu-1.15.0.zip

        1.9 - Leetcode downloader

        CLI app to download leetcode submissions

        Features

        • CLI and bzl code to generate submission docs
        • Tampermonkey script to download submissions (Doesn’t work because the API was removed)
        • CLI to download submissions (Doesn’t work because of bot protection)

        Usage

        Generate submission from a submission file

        bazel run go/leetcode_downloader -- \
            --submissions-file "${PWD}/out/submissions.json" \
            --root-dir "${PWD}" \
            generate
        

        Help

        Usage of flags:
          -base_url string
            	 (default "https://leetcode.com")
          -cookie string
        
          -limit uint
            	 (default 20)
          -offset uint
        
          -root-dir string
            	 (default "${PWD}")
          -submissions-file string
        

        1.9.1 - Bzl

        Bazel code

        1.9.1.1 - al_leetcode_submissions

        al_leetcode_submissions

        load("@com_alwaldend_src//projects/leetcode_downloader/main/bzl:al_leetcode_submissions.bzl", "al_leetcode_submissions")
        
        al_leetcode_submissions(name, srcs, visibility, **kwargs)
        

        Generate leetcode submission targets

        PARAMETERS

        Name Description Default Value
        name generated md archive name none
        srcs leetcode submission configs none
        visibility visibility None
        kwargs kwargs for al_template_files none

        1.9.2 - Proto

        Protobuf contracts

        1.9.2.1 - contracts

        Proto docs for contracts.proto

        Java

        load("@rules_java//java:defs.bzl", "java_library")
        
        java_library(
            name = "name",
            deps = [
                "@com_alwaldend_src//projects/leetcode_downloader/main/proto:contracts_java_library",
            ],
        )
        

        Golang

        load("@rules_go//go:def.bzl", "go_library")
        
        go_library(
            name = "name",
            deps = [
                "@com_alwaldend_src//projects/leetcode_downloader/main/proto:proto",
            ],
        )
        

        Proto

        syntax = "proto3";
        
        option go_package = "git.alwaldend.com/src/projects/leetcode_downloader/main/proto/contracts";
        
        enum CliAction {
          DOWNLOAD = 0;
          GENERATE = 1;
          UPDATE = 2;
        }
        
        message Config {
          string base_url = 1;
          string cookie = 2;
          repeated string action_args = 4;
          CliAction action = 5;
          uint64 offset = 6;
          uint64 limit = 7;
          map<string, SubmissionConfig> submissions = 8;
          string root_dir = 9;
          map<string, string> headers = 11;
          string submissions_file = 12;
          bool write_code = 13;
        }
        
        message SubmissionConfig {
          string dir = 1;
          string extension = 2;
          repeated string types = 3;
        }
        
        message Submission {
          uint64 id = 1;
          string status_display = 2;
          string lang = 3;
          uint64 question_id = 4;
          string title_slug = 5;
          string code = 6;
          string title = 7;
          string url = 8;
          string lang_name = 9;
          // string time = 10;
          uint64 timestamp = 11;
          uint64 status = 12;
          string runtime = 13;
          string is_pending = 14;
          string memory = 15;
          string compare_result = 16;
          bool has_notes = 17;
          uint64 flag_type = 18;
        }
        
        message SubmissonsResponse {
          repeated Submission submissions_dump = 1;
          bool has_next = 2;
          string last_key = 3;
        }
        message SubmissonsStorage {
          repeated Submission submissions = 1;
        }
        

        1.9.3 - Releases

        Releases

        • Add deploy to dockerhub, add //tools/oras
        • Add missing features to the Pomodoro app, update project readmes, add github pages
        • Move all remaining code to main
        • Move a portion of tool code to main
        • Move leetcode downloader go code to main
        • Add tools/nogo
        • Use separate lock files for each golang tool
        • Start fixing go mod tidy errors
        • Move some code to main
        • Remove sites taxonomy, start adding xray_manager
        • Add release_page generation, remove redundant release templates
        • Remove contracts tree
        • Allow docs to put content outside of docs, refactor git to just use .git directly
        • Add cross-compilation, move leetcode downloader contracts out of //contracts
        • Refactor release templates into partials, add release cards
        • Add more taxonomies, remove docs tree, move alwaldend.com to projects
        • Rename proto to contracts, add tools/proto add proto docs
        • Remove bazel target docs, add tools/docs, tag projects properly
        • Remove changelogs, ignore irrelevant directories in docs
        • Remove bzl tree

        • release_deps.dot
        • contracts.proto
        • leetcode_downloader_tampermonkey.js
        • leetcode_downloader_crossbinary.aix_ppc64
        • leetcode_downloader_crossbinary.dragonfly_amd64
        • leetcode_downloader_crossbinary.freebsd_386
        • leetcode_downloader_crossbinary.freebsd_amd64
        • leetcode_downloader_crossbinary.freebsd_arm
        • leetcode_downloader_crossbinary.freebsd_arm64
        • leetcode_downloader_crossbinary.illumos_amd64
        • leetcode_downloader_crossbinary.js_wasm
        • leetcode_downloader_crossbinary.linux_386
        • leetcode_downloader_crossbinary.linux_amd64
        • leetcode_downloader_crossbinary.linux_arm
        • leetcode_downloader_crossbinary.linux_arm64
        • leetcode_downloader_crossbinary.linux_mips
        • leetcode_downloader_crossbinary.linux_mips64
        • leetcode_downloader_crossbinary.linux_mips64le
        • leetcode_downloader_crossbinary.linux_mipsle
        • leetcode_downloader_crossbinary.linux_ppc64
        • leetcode_downloader_crossbinary.linux_ppc64le
        • leetcode_downloader_crossbinary.linux_riscv64
        • leetcode_downloader_crossbinary.linux_s390x
        • leetcode_downloader_crossbinary.netbsd_386
        • leetcode_downloader_crossbinary.netbsd_amd64
        • leetcode_downloader_crossbinary.netbsd_arm
        • leetcode_downloader_crossbinary.netbsd_arm64
        • leetcode_downloader_crossbinary.openbsd_386
        • leetcode_downloader_crossbinary.openbsd_amd64
        • leetcode_downloader_crossbinary.openbsd_arm
        • leetcode_downloader_crossbinary.openbsd_arm64
        • leetcode_downloader_crossbinary.plan9_386
        • leetcode_downloader_crossbinary.plan9_amd64
        • leetcode_downloader_crossbinary.plan9_arm
        • leetcode_downloader_crossbinary.solaris_amd64
        • leetcode_downloader_crossbinary.wasip1_wasm
        • leetcode_downloader_crossbinary.windows_386
        • leetcode_downloader_crossbinary.windows_amd64
        • leetcode_downloader_crossbinary.windows_arm
        • leetcode_downloader_crossbinary.windows_arm64

        1.9.3.1 - head

        Release head

        • Add deploy to dockerhub, add //tools/oras
        • Add missing features to the Pomodoro app, update project readmes, add github pages
        • Move all remaining code to main
        • Move a portion of tool code to main
        • Move leetcode downloader go code to main
        • Add tools/nogo
        • Use separate lock files for each golang tool
        • Start fixing go mod tidy errors
        • Move some code to main
        • Remove sites taxonomy, start adding xray_manager
        • Add release_page generation, remove redundant release templates
        • Remove contracts tree
        • Allow docs to put content outside of docs, refactor git to just use .git directly
        • Add cross-compilation, move leetcode downloader contracts out of //contracts
        • Refactor release templates into partials, add release cards
        • Add more taxonomies, remove docs tree, move alwaldend.com to projects
        • Rename proto to contracts, add tools/proto add proto docs
        • Remove bazel target docs, add tools/docs, tag projects properly
        • Remove changelogs, ignore irrelevant directories in docs
        • Remove bzl tree

        • release_deps.dot
        • contracts.proto
        • leetcode_downloader_tampermonkey.js
        • leetcode_downloader_crossbinary.aix_ppc64
        • leetcode_downloader_crossbinary.dragonfly_amd64
        • leetcode_downloader_crossbinary.freebsd_386
        • leetcode_downloader_crossbinary.freebsd_amd64
        • leetcode_downloader_crossbinary.freebsd_arm
        • leetcode_downloader_crossbinary.freebsd_arm64
        • leetcode_downloader_crossbinary.illumos_amd64
        • leetcode_downloader_crossbinary.js_wasm
        • leetcode_downloader_crossbinary.linux_386
        • leetcode_downloader_crossbinary.linux_amd64
        • leetcode_downloader_crossbinary.linux_arm
        • leetcode_downloader_crossbinary.linux_arm64
        • leetcode_downloader_crossbinary.linux_mips
        • leetcode_downloader_crossbinary.linux_mips64
        • leetcode_downloader_crossbinary.linux_mips64le
        • leetcode_downloader_crossbinary.linux_mipsle
        • leetcode_downloader_crossbinary.linux_ppc64
        • leetcode_downloader_crossbinary.linux_ppc64le
        • leetcode_downloader_crossbinary.linux_riscv64
        • leetcode_downloader_crossbinary.linux_s390x
        • leetcode_downloader_crossbinary.netbsd_386
        • leetcode_downloader_crossbinary.netbsd_amd64
        • leetcode_downloader_crossbinary.netbsd_arm
        • leetcode_downloader_crossbinary.netbsd_arm64
        • leetcode_downloader_crossbinary.openbsd_386
        • leetcode_downloader_crossbinary.openbsd_amd64
        • leetcode_downloader_crossbinary.openbsd_arm
        • leetcode_downloader_crossbinary.openbsd_arm64
        • leetcode_downloader_crossbinary.plan9_386
        • leetcode_downloader_crossbinary.plan9_amd64
        • leetcode_downloader_crossbinary.plan9_arm
        • leetcode_downloader_crossbinary.solaris_amd64
        • leetcode_downloader_crossbinary.wasip1_wasm
        • leetcode_downloader_crossbinary.windows_386
        • leetcode_downloader_crossbinary.windows_amd64
        • leetcode_downloader_crossbinary.windows_arm
        • leetcode_downloader_crossbinary.windows_arm64

        1.10 - Nexus security plugin

        Security plugin for Sonatype Nexus 3

        Features

        TODO

        • Migrate the code to Bazel

        1.11 - Sri

        Subresource Integrity calculator

        Features

        • Cli app that calculates SRI using OpenSSL
        • C, OpenSSL

        Usage

        Usage: sri [OPTION...]
        Generate sri of a file
        
        Example:
            bazel run //projects/sri -- --digest sha256 --file ${PWD}/README.md
        
          -d, --digest=String        Digest type (sha256, for example)
          -f, --file=Path            Path to the file to parse
          -?, --help                 Give this help list
              --usage                Give a short usage message
        

        1.11.1 - Releases

        Releases

        • Add deploy to dockerhub, add //tools/oras
        • Add missing features to the Pomodoro app, update project readmes, add github pages
        • Move all remaining code to main
        • Move some code to main
        • Add release_page generation, remove redundant release templates
        • Allow docs to put content outside of docs, refactor git to just use .git directly
        • Add cross-compilation, move leetcode downloader contracts out of //contracts
        • Refactor release templates into partials, add release cards
        • Add more taxonomies, remove docs tree, move alwaldend.com to projects
        • Remove bazel target docs, add tools/docs, tag projects properly
        • Remove changelogs, ignore irrelevant directories in docs
        • Move another group of rules to tools/
        • Move a group of rules to tools/
        • Remove c and cpp trees

        • release_deps.dot
        • sri

        1.11.1.1 - head

        Release head

        • Add deploy to dockerhub, add //tools/oras
        • Add missing features to the Pomodoro app, update project readmes, add github pages
        • Move all remaining code to main
        • Move some code to main
        • Add release_page generation, remove redundant release templates
        • Allow docs to put content outside of docs, refactor git to just use .git directly
        • Add cross-compilation, move leetcode downloader contracts out of //contracts
        • Refactor release templates into partials, add release cards
        • Add more taxonomies, remove docs tree, move alwaldend.com to projects
        • Remove bazel target docs, add tools/docs, tag projects properly
        • Remove changelogs, ignore irrelevant directories in docs
        • Move another group of rules to tools/
        • Move a group of rules to tools/
        • Remove c and cpp trees

        • release_deps.dot
        • sri

        1.12 - Useless QT GUI

        Desktop GUI written with C++

        Features

        • Desktop GUI
        • C++, Qt

        TODO

        • Remove pkg_tar
        • Fix CI build
        • Add some screenshots

        2 - Infra

        Infrastructure tree

        This tree contains IaC

        Requirements

        • MUST NOT be public
        • MUST NOT be published
        • MUST NOT be used in builds

        2.1 - Alwaldend.com

        Alwaldend.com infrastructure

        2.1.1 - Dc1

        Infrastructure for dc1.alwaldend.com

        2.1.1.1 - Cl1

        Infrastructure for cl1.dc1.alwaldend.com

        Deployment

        • Setup the host:
          bazel run //infra/alwaldend.com/dc1/cl1/ansible:deploy
          
        • Deploy the chart:
          ssh -NR 127.0.0.1:6443:127.0.0.1:6443 pi1.cl1.dc1.alwaldend.com &
          bazel run //infra/alwaldend.com/dc1/cl1/helm:deploy
          

        2.1.1.2 - Mikrotik

        Mikrotik setup for dc1.alwaldend.com

        Deployment

        Manual export and import through Winbox

        Exports

        Router1

        # 2025-09-14 10:53:06 by RouterOS 7.19.4
        /interface bridge
        add admin-mac=78:9A:18:38:6C:CA auto-mac=no comment="bridge1 (wired)" name=bridge1
        add comment="bridge2 (wireless)" name=bridge2
        /interface ethernet
        set [ find default-name=ether1 ] comment=ether1 l2mtu=1500 mac-address=F4:28:53:7F:A4:59
        set [ find default-name=ether2 ] comment=ether2
        set [ find default-name=ether3 ] comment=ether3
        set [ find default-name=ether4 ] comment=ether4
        set [ find default-name=ether5 ] comment=ether5
        /interface wifi
        set [ find default-name=wifi1 ] channel.frequency=5000-5400 .skip-dfs-channels=10min-cac comment="wifi1 (5GHz)" \
            configuration.country=Russia .mode=ap .ssid=divinity-5GHz datapath.client-isolation=yes disabled=no \
            security.authentication-types=wpa2-psk,wpa3-psk .connect-priority=0 .ft=yes .ft-over-ds=yes
        set [ find default-name=wifi2 ] channel.skip-dfs-channels=10min-cac comment="wifi2 (2GHz)" configuration.country=Russia .mode=ap \
            .ssid=divinity-2GHz datapath.client-isolation=yes disabled=no security.authentication-types=wpa2-psk,wpa3-psk \
            .connect-priority=0 .ft=yes .ft-over-ds=yes
        /interface list
        add comment=defconf name=WAN
        add comment=defconf name=LAN
        add name=accept-forward-WAN
        add name=accept-input-DNS
        add name=accept-input-DHCP-server
        add name=accept-input-ICMP
        add name=accept-input-winbox
        add name=accept-input-web-ui
        add name=accept-input-mikrotik-neighbor-discovery
        /ip pool
        add comment=bridge1 name=bridge1 ranges=192.168.1.10-192.168.1.254
        add comment=bridge2 name=bridge2 ranges=192.168.2.10-192.168.2.254
        /ip dhcp-server
        add address-pool=bridge1 comment=bridge1 interface=bridge1 lease-time=10m name=bridge1
        add address-pool=bridge2 interface=bridge2 name=bridge2
        /ipv6 pool
        add name=dc01 prefix=fd2e:546d:5738::/48 prefix-length=64
        /interface bridge port
        add bridge=bridge1 comment=bridge1-ether2 interface=ether2
        add bridge=bridge1 comment=bridge1-ether3 interface=ether3
        add bridge=bridge1 comment=bridge1-ether4 interface=ether4
        add bridge=bridge1 comment=bridge1-ether5 interface=ether5
        add bridge=bridge2 comment=bridge2-wifi1 interface=wifi1
        add bridge=bridge2 comment=bridge2-wifi2 interface=wifi2
        /ip neighbor discovery-settings
        set discover-interface-list=LAN
        /interface detect-internet
        set detect-interface-list=WAN
        /interface list member
        add interface=bridge1 list=LAN
        add interface=ether1 list=WAN
        add interface=bridge2 list=LAN
        add interface=bridge2 list=accept-forward-WAN
        add interface=bridge1 list=accept-forward-WAN
        add interface=bridge1 list=accept-input-DNS
        add interface=bridge2 list=accept-input-DNS
        add interface=bridge1 list=accept-input-DHCP-server
        add interface=bridge2 list=accept-input-DHCP-server
        add interface=bridge1 list=accept-input-ICMP
        add interface=bridge2 list=accept-input-ICMP
        add interface=bridge1 list=accept-input-winbox
        add interface=bridge1 list=accept-input-web-ui
        add interface=bridge1 list=accept-input-mikrotik-neighbor-discovery
        /interface ovpn-server server
        add mac-address=FE:B3:B4:C4:A4:48 name=ovpn-server1
        /ip address
        add address=192.168.1.1/24 comment=bridge1 interface=bridge1 network=192.168.1.0
        add address=192.168.2.1/24 comment=bridge2 interface=bridge2 network=192.168.2.0
        /ip dhcp-client
        add comment=defconf interface=ether1 use-peer-dns=no
        /ip dhcp-server network
        add address=192.168.1.0/24 comment=defconf dns-server=192.168.1.1 gateway=192.168.1.1
        add address=192.168.2.0/24 dns-server=192.168.2.1 gateway=192.168.2.1
        /ip dns
        set allow-remote-requests=yes servers=1.1.1.2,1.0.0.2 use-doh-server=https://odoh.cloudflare-dns.com/dns-query verify-doh-cert=\
            yes
        /ip dns static
        add address=192.168.88.1 comment=defconf name=router.lan type=A
        /ip firewall filter
        add action=accept chain=input comment="defconf: accept established,related,untracked" connection-state=\
            established,related,untracked
        add action=drop chain=input comment="defconf: drop invalid" connection-state=invalid log-prefix=drop-invalid
        add action=accept chain=input comment="defconf: accept ICMP" in-interface-list=accept-input-ICMP protocol=icmp
        add action=accept chain=input comment="defconf: accept to local loopback (for CAPsMAN)" dst-address=127.0.0.1
        add action=drop chain=input comment="defconf: drop all not coming from LAN" in-interface-list=!LAN log-prefix=\
            drop-not-coming-from-lan
        add action=accept chain=forward comment="defconf: accept in ipsec policy" ipsec-policy=in,ipsec
        add action=accept chain=forward comment="defconf: accept out ipsec policy" ipsec-policy=out,ipsec
        add action=fasttrack-connection chain=forward comment="defconf: fasttrack" connection-state=established,related hw-offload=yes
        add action=accept chain=forward comment="defconf: accept established,related, untracked" connection-state=\
            established,related,untracked
        add action=drop chain=forward comment="defconf: drop invalid" connection-state=invalid log-prefix=drop-invalid
        add action=drop chain=forward comment="defconf: drop all from WAN not DSTNATed" connection-nat-state=!dstnat connection-state=\
            new in-interface-list=WAN log-prefix=drop-from-wan-not-dstnated
        add action=accept chain=input in-interface-list=WAN protocol=gre
        add action=accept chain=forward comment="accept forward WAN" in-interface-list=accept-forward-WAN out-interface-list=WAN
        add action=accept chain=input comment="accept input DNS (udp)" dst-port=53 in-interface-list=accept-input-DNS protocol=udp
        add action=accept chain=input comment="accept input DNS (tcp)" dst-port=53 in-interface-list=accept-input-DNS protocol=tcp
        add action=accept chain=input comment="accept input DHCP-server" dst-port=67 in-interface-list=accept-input-DHCP-server \
            log-prefix=accept-DHCP protocol=udp
        add action=accept chain=input comment="accept input winbox (tcp)" dst-port=8291 in-interface-list=accept-input-winbox protocol=\
            tcp
        add action=accept chain=input comment="accept input winbox (udp)" dst-port=20561 in-interface-list=accept-input-winbox protocol=\
            udp
        add action=accept chain=input comment="accept input web ui" dst-port=80,443 in-interface-list=accept-input-web-ui protocol=tcp
        add action=accept chain=input comment="accept input mikrotik neighbor discovery" dst-port=5678 in-interface-list=\
            accept-input-mikrotik-neighbor-discovery protocol=udp
        add action=drop chain=forward comment="drop forward" log=yes log-prefix=drop-forward
        add action=drop chain=input comment="drop input" log=yes log-prefix=drop-input
        /ip firewall nat
        add action=masquerade chain=srcnat comment="defconf: masquerade" ipsec-policy=out,none out-interface-list=WAN
        /ip ipsec profile
        set [ find default=yes ] dpd-interval=2m dpd-maximum-failures=5
        /ip service
        set www disabled=yes
        set www-ssl certificate=ssl-web-management disabled=no
        /ipv6 address
        add address=::1 from-pool=dc01 interface=bridge1
        add address=::1 from-pool=dc01 interface=bridge2
        /ipv6 firewall address-list
        add address=::/128 comment="defconf: unspecified address" list=bad_ipv6
        add address=::1/128 comment="defconf: lo" list=bad_ipv6
        add address=fec0::/10 comment="defconf: site-local" list=bad_ipv6
        add address=::ffff:0.0.0.0/96 comment="defconf: ipv4-mapped" list=bad_ipv6
        add address=::/96 comment="defconf: ipv4 compat" list=bad_ipv6
        add address=100::/64 comment="defconf: discard only " list=bad_ipv6
        add address=2001:db8::/32 comment="defconf: documentation" list=bad_ipv6
        add address=2001:10::/28 comment="defconf: ORCHID" list=bad_ipv6
        add address=3ffe::/16 comment="defconf: 6bone" list=bad_ipv6
        /ipv6 firewall filter
        add action=accept chain=input comment="defconf: accept established,related,untracked" connection-state=\
            established,related,untracked
        add action=drop chain=input comment="defconf: drop invalid" connection-state=invalid
        add action=accept chain=input comment="defconf: accept ICMPv6" in-interface-list=accept-input-ICMP protocol=icmpv6
        add action=accept chain=input comment="defconf: accept UDP traceroute" dst-port=33434-33534 protocol=udp
        add action=accept chain=input comment="defconf: accept DHCPv6-Client prefix delegation." dst-port=546 protocol=udp src-address=\
            fe80::/10
        add action=accept chain=input comment="defconf: accept IKE" dst-port=500,4500 protocol=udp
        add action=accept chain=input comment="defconf: accept ipsec AH" protocol=ipsec-ah
        add action=accept chain=input comment="defconf: accept ipsec ESP" protocol=ipsec-esp
        add action=accept chain=input comment="defconf: accept all that matches ipsec policy" ipsec-policy=in,ipsec
        add action=drop chain=input comment="defconf: drop everything else not coming from LAN" in-interface-list=!LAN
        add action=accept chain=forward comment="defconf: accept established,related,untracked" connection-state=\
            established,related,untracked
        add action=drop chain=forward comment="defconf: drop invalid" connection-state=invalid
        add action=drop chain=forward comment="defconf: drop packets with bad src ipv6" src-address-list=bad_ipv6
        add action=drop chain=forward comment="defconf: drop packets with bad dst ipv6" dst-address-list=bad_ipv6
        add action=drop chain=forward comment="defconf: rfc4890 drop hop-limit=1" hop-limit=equal:1 protocol=icmpv6
        add action=accept chain=forward comment="defconf: accept ICMPv6" in-interface-list=accept-input-ICMP protocol=icmpv6
        add action=accept chain=forward comment="defconf: accept HIP" protocol=139
        add action=accept chain=forward comment="defconf: accept IKE" dst-port=500,4500 protocol=udp
        add action=accept chain=forward comment="defconf: accept ipsec AH" protocol=ipsec-ah
        add action=accept chain=forward comment="defconf: accept ipsec ESP" protocol=ipsec-esp
        add action=accept chain=forward comment="defconf: accept all that matches ipsec policy" ipsec-policy=in,ipsec
        add action=drop chain=forward comment="defconf: drop everything else not coming from LAN" in-interface-list=!LAN
        add action=accept chain=forward comment="accept forward WAN" in-interface-list=accept-forward-WAN out-interface-list=WAN
        add action=accept chain=input comment="accept input DNS (udp)" dst-port=53 in-interface-list=accept-input-DNS protocol=udp
        add action=accept chain=input comment="accept input DNS (tcp)" dst-port=53 in-interface-list=accept-input-DNS protocol=tcp
        add action=accept chain=input comment="accept input winbox (tcp)" dst-port=8291 in-interface-list=accept-input-winbox protocol=\
            tcp
        add action=accept chain=input comment="accept input winbox (udp)" dst-port=20561 in-interface-list=accept-input-winbox protocol=\
            udp
        add action=accept chain=input comment="accept input web ui" dst-port=80,443 in-interface-list=accept-input-web-ui protocol=tcp
        add action=accept chain=input comment="accept input mikrotik neighbor discovery" dst-port=5678 in-interface-list=\
            accept-input-mikrotik-neighbor-discovery protocol=udp
        add action=drop chain=forward comment="drop forward" log=yes log-prefix=drop-forward-ipv6
        add action=drop chain=input comment="drop input" log=yes log-prefix=drop-input-ipv6
        /ipv6 nd
        set [ find default=yes ] interface=bridge1
        add interface=bridge2
        /system clock
        set time-zone-name=Europe/Moscow
        /system identity
        set name=router1.dc1.alwaldend.com
        /system routerboard settings
        set auto-upgrade=yes
        /tool mac-server
        set allowed-interface-list=LAN
        /tool mac-server mac-winbox
        set allowed-interface-list=LAN
        

        Router2

        # 2025-09-07 11:04:01 by RouterOS 7.19.4
        # model = L009UiGS-2HaxD
        /interface bridge
        add name=bridge01
        /port
        set 0 name=serial0
        /interface bridge port
        add bridge=bridge01 interface=ether2
        add bridge=bridge01 interface=ether3
        add bridge=bridge01 interface=ether4
        add bridge=bridge01 interface=ether5
        add bridge=bridge01 interface=ether6
        add bridge=bridge01 interface=ether7
        add bridge=bridge01 interface=ether8
        add bridge=bridge01 interface=ether1
        /ip neighbor discovery-settings
        set discover-interface-list=!dynamic
        /ipv6 settings
        set accept-router-advertisements=yes
        /ip dhcp-client
        add interface=bridge01
        /system clock
        set time-zone-name=Europe/Moscow
        /system identity
        set name=router02.dc01.alwaldend.com
        /system routerboard settings
        set enter-setup-on=delete-key
        

        2.1.2 - Dc2

        Infrastructure for dc2.alwaldend.com

        2.1.3 - Dns

        Dns setup for alwaldend.com

        Deployment

        • Setup environment variables from creds.json.tpl
        • Modify dnsconfig.js
        • Preview changes:
          bazel run //infra/alwaldend.com/dns:preview
          
        • Deploy changes:
          bazel run //infra/alwaldend.com/dns:deploy
          

        BIND file

        $TTL 10800
        ; generated with dnscontrol 2025-12-14T16:56:39+03:00
        @          300   IN SOA   DEFAULT_NOT_SET. DEFAULT_NOT_SET. 2025121400 3600 600 604800 1440
                   300   IN NS    malavika.ns.cloudflare.com.
                   300   IN NS    terry.ns.cloudflare.com.
                   300   IN A     185.199.108.153
                   300   IN A     185.199.109.153
                   300   IN A     185.199.110.153
                   300   IN A     185.199.111.153
                   300   IN AAAA  2606:50c0:8000::153
                   300   IN AAAA  2606:50c0:8001::153
                   300   IN AAAA  2606:50c0:8002::153
                   300   IN AAAA  2606:50c0:8003::153
                         IN MX    0 mail.tutanota.de.
                         IN TXT   "t-verify=518bd0ae347aa5e3bcca726766106ad3"
                         IN TXT   "v=spf1 include:spf.tutanota.de -all"
        _dmarc           IN TXT   "v=DMARC1; p=quarantine; adkim=s"
        s1._domainkey    IN CNAME s1.domainkey.tutanota.de.
        s2._domainkey    IN CNAME s2.domainkey.tutanota.de.
        _mta-sts         IN CNAME mta-sts.tutanota.de.
        pi1.cl1.dc1 300  IN A     192.168.1.250
                   300   IN AAAA  fd2e:546d:5738:0:e65d:726e:80d9:fef1
        rancher.cl1.dc1  IN CNAME pi1.cl1.dc1.
        router1.dc1 300  IN AAAA  fd2e:546d:5738::1
        mta-sts          IN CNAME mta-sts.tutanota.de.
        simplelogin      IN MX    10 mx1.simplelogin.co.
                         IN MX    20 mx2.simplelogin.co.
                         IN TXT   "sl-verification=bxfzzfjiggzsxyzxhhmkmjqkaskjgy"
                         IN TXT   "v=spf1 include:simplelogin.co ~all"
        _dmarc.simplelogin IN TXT "v=DMARC1; p=quarantine; pct=100; adkim=s; aspf=s"
        dkim._domainkey.simplelogin IN CNAME dkim._domainkey.simplelogin.co.
        dkim02._domainkey.simplelogin IN CNAME dkim02._domainkey.simplelogin.co.
        dkim03._domainkey.simplelogin IN CNAME dkim03._domainkey.simplelogin.co.
        

        3 - Tools

        Tools tree

        This tree contains tools that are used inside the repo

        Requirements

        • MUST NOT be public (except toolchain types)
        • MUST NOT be published
        • MUST NOT be used in builds
        • MUST be available to the whole repo (visibility = ["//:__subpackages__"])
        • MAY be used in tests

        3.1 - Android

        Android

        3.2 - Ansible

        Bazel rules for ansible

        3.2.1 - Bzl

        Bazel code

        3.2.1.1 - al_ansible_binaries

        al_ansible_binaries

        load("@com_alwaldend_src//tools/ansible/main/bzl:al_ansible_binaries.bzl", "al_ansible_binaries")
        
        al_ansible_binaries(name, args, visibility, **kwargs)
        

        Generate a binary for earch ansible command

        PARAMETERS

        Name Description Default Value
        name name prefix none
        args specific kwargs {}
        visibility visibility None
        kwargs common arguments none

        3.2.1.2 - al_ansible_binary

        al_ansible_binary

        load("@com_alwaldend_src//tools/ansible/main/bzl:al_ansible_binary.bzl", "al_ansible_binary")
        
        al_ansible_binary(name, data, ansible, arguments, process_name)
        

        Run an ansible command

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        data Data List of labels optional []
        ansible Ansible executable Dictionary: String -> Label optional {"ansible": "@com_alwaldend_src//tools/ansible", "ansible_config": "@com_alwaldend_src//tools/ansible:ansible_config", "ansible_console": "@com_alwaldend_src//tools/ansible:ansible_console", "ansible_doc": "@com_alwaldend_src//tools/ansible:ansible_doc", "ansible_galaxy": "@com_alwaldend_src//tools/ansible:ansible_galaxy", "ansible_inventory": "@com_alwaldend_src//tools/ansible:ansible_inventory", "ansible_playbook": "@com_alwaldend_src//tools/ansible:ansible_playbook", "ansible_pull": "@com_alwaldend_src//tools/ansible:ansible_pull", "ansible_test": "@com_alwaldend_src//tools/ansible:ansible_test", "ansible_vault": "@com_alwaldend_src//tools/ansible:ansible_vault"}
        arguments Ansible arguments List of strings optional []
        process_name Process name String required

        3.2.1.3 - al_ansible_extension

        al_ansible_extension

        al_ansible_extension = use_extension("@com_alwaldend_src//tools/ansible/main/bzl:al_ansible_extension.bzl", "al_ansible_extension")
        al_ansible_extension.lock(name, lock)
        

        Ansible extensions

        TAG CLASSES

        lock

        Attributes

        Name Description Type Mandatory Default
        name Name prefix Name required
        lock Ansible lock path Label required

        3.2.1.4 - al_ansible_role

        al_ansible_role

        load("@com_alwaldend_src//tools/ansible/main/bzl:al_ansible_role.bzl", "al_ansible_role")
        
        al_ansible_role(name, srcs, visibility)
        

        Create targets for an ansible role

        PARAMETERS

        Name Description Default Value
        name name prefix none
        srcs role sources none
        visibility resulting archive visibility none

        3.2.1.5 - al_ansible_scripts

        3.3 - Bazel configs

        Bazel config targets

        3.4 - Bazel contracts

        Bazel contracts

        3.4.1 - Bzl

        Bazel code

        3.4.1.1 - al_bazel_contracts_extension

        al_bazel_contracts_extension

        al_bazel_contracts_extension = use_extension("@com_alwaldend_src//tools/bazel_contracts/main/bzl:al_bazel_contracts_extension.bzl", "al_bazel_contracts_extension")
        al_bazel_contracts_extension.download(name, base_url, contracts, integrity, prefix, version)
        

        Create a repo of bazel contracts

        TAG CLASSES

        download

        Attributes

        Name Description Type Mandatory Default
        name Name Name required
        base_url Base url String optional ""
        contracts List of contract paths List of strings optional ["action_cache.proto", "bazel_flags.proto", "builtin.proto", "cache_salt.proto", "crash_debugging.proto", "crosstool_config.proto", "deps.proto", "desugar_deps.proto", "execution_graph.proto", "execution_statistics.proto", "extra_actions_base.proto", "file_invalidation_data.proto", "java_compilation.proto", "memory_pressure.proto", "option_filters.proto", "remote_scrubbing.proto", "stardoc_output.proto", "strategy_policy.proto", "test_status.proto", "worker_protocol.proto", "xcode_config.proto", "project/enforcement_policy.proto"]
        integrity Integrity Dictionary: String -> String optional {}
        prefix Prefix for the contracts inside the repo String optional ""
        version Version String optional ""

        3.4.1.2 - al_bazel_contracts_list

        3.4.1.3 - al_bazel_contracts_repo

        al_bazel_contracts_repo

        load("@com_alwaldend_src//tools/bazel_contracts/main/bzl:al_bazel_contracts_repo.bzl", "al_bazel_contracts_repo")
        
        al_bazel_contracts_repo(name, base_url, contracts, integrity, repo_mapping)
        

        Bazel contracts repo

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this repository. Name required
        base_url Base url String required
        contracts Contract paths List of strings required
        integrity Integrity, keys are contract paths, values are integrity Dictionary: String -> String required
        repo_mapping In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.

        For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target, it should actually resolve that dependency within globally-declared @bar (@bar//some:target).

        This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension’s implementation function).
        Dictionary: String -> String optional

        3.4.1.4 - al_bazel_contracts_versions

        3.5 - Bazel shell worker

        Bazel worker that runs shell commands

        3.5.1 - Bzl

        Bazel code

        3.5.1.1 - al_genrule

        al_genrule

        load("@com_alwaldend_src//tools/shell_worker/main/bzl:al_genrule.bzl", "al_genrule")
        
        al_genrule(test, executable, **kwargs)
        

        Generate al_genrule target

        PARAMETERS

        Name Description Default Value
        test If set, use al_genrule_test False
        executable if set, use al_genrule_executable False
        kwargs kwargs for the rule none

        3.5.1.2 - al_genrule_rule

        al_genrule_executable

        load("@com_alwaldend_src//tools/shell_worker/main/bzl:al_genrule_rule.bzl", "al_genrule_executable")
        
        al_genrule_executable(name, srcs, data, outs, cmd, set_flags, shell, tools, worker)
        

        Build executable using shell worker

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        srcs Sources, will not be added to runfiles List of labels optional []
        data Data, will be added to runfiles List of labels optional []
        outs Outputs List of labels; nonconfigurable required
        cmd Script to execute String required
        set_flags set flags List of strings optional ["-eux"]
        shell shell to use String optional "/bin/sh"
        tools Tools, will be added to runfiles List of labels optional []
        worker Worker binary Label optional "@com_alwaldend_src//tools/shell_worker"

        al_genrule_regular

        load("@com_alwaldend_src//tools/shell_worker/main/bzl:al_genrule_rule.bzl", "al_genrule_regular")
        
        al_genrule_regular(name, srcs, data, outs, cmd, set_flags, shell, tools, worker)
        

        Build shell worker rule

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        srcs Sources, will not be added to runfiles List of labels optional []
        data Data, will be added to runfiles List of labels optional []
        outs Outputs List of labels; nonconfigurable required
        cmd Script to execute String required
        set_flags set flags List of strings optional ["-eux"]
        shell shell to use String optional "/bin/sh"
        tools Tools, will be added to runfiles List of labels optional []
        worker Worker binary Label optional "@com_alwaldend_src//tools/shell_worker"

        al_genrule_test

        load("@com_alwaldend_src//tools/shell_worker/main/bzl:al_genrule_rule.bzl", "al_genrule_test")
        
        al_genrule_test(name, srcs, data, outs, cmd, set_flags, shell, tools, worker)
        

        Test using shell worker

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        srcs Sources, will not be added to runfiles List of labels optional []
        data Data, will be added to runfiles List of labels optional []
        outs Outputs List of labels; nonconfigurable required
        cmd Script to execute String required
        set_flags set flags List of strings optional ["-eux"]
        shell shell to use String optional "/bin/sh"
        tools Tools, will be added to runfiles List of labels optional []
        worker Worker binary Label optional "@com_alwaldend_src//tools/shell_worker"

        3.6 - Bazelrc

        Bazelrc files

        Usage

        bazel run //tools/bazelrc:preset.update
        

        3.7 - Black

        Black

        3.8 - Buf

        Buf

        3.10 - Bzl

        Bazel rules related to Bazel itself

        3.10.1 - Bzl

        Bazel code

        3.10.1.1 - al_alias_map

        al_alias_map

        load("@com_alwaldend_src//tools/bzl/main/bzl:al_alias_map.bzl", "al_alias_map")
        
        al_alias_map(aliases, visibility)
        

        Generate aliases from an alias map

        PARAMETERS

        Name Description Default Value
        aliases alias map, keys are names, values are alias arguments none
        visibility default visibility ["//:__subpackages__"]

        3.10.1.2 - al_bzl_generate_repository

        al_bzl_generate_repository

        load("@com_alwaldend_src//tools/bzl/main/bzl:al_bzl_generate_repository.bzl", "al_bzl_generate_repository")
        
        al_bzl_generate_repository(name, files, repo_mapping)
        

        Generate a repository

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this repository. Name required
        files Files to generate, keys are paths, values are file contents Dictionary: String -> String optional {}
        repo_mapping In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.

        For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target, it should actually resolve that dependency within globally-declared @bar (@bar//some:target).

        This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension’s implementation function).
        Dictionary: String -> String optional

        3.10.1.3 - al_bzl_library_map

        al_bzl_library_map

        load("@com_alwaldend_src//tools/bzl/main/bzl:al_bzl_library_map.bzl", "al_bzl_library_map")
        
        al_bzl_library_map(name, visibility, libs, deps, **kwargs)
        

        Create bzl_library targets from a map

        PARAMETERS

        Name Description Default Value
        name combined bzl_library target name none
        visibility

        -

        None
        libs bzl_library names {}
        deps other al_bzl_library_map targets []
        kwargs bzl_library kwargs none

        3.10.1.4 - al_bzl_target_doc

        al_bzl_target_doc

        load("@com_alwaldend_src//tools/bzl/main/bzl:al_bzl_target_doc.bzl", "al_bzl_target_doc")
        
        al_bzl_target_doc(name, visibility, subpackages)
        

        Document bazel targets

        PARAMETERS

        Name Description Default Value
        name target name none
        visibility

        -

        none
        subpackages list of subpackages []

        3.10.1.5 - al_genquery_write_to_source_file

        al_genquery_write_to_source_file

        load("@com_alwaldend_src//tools/bzl/main/bzl:al_genquery_write_to_source_file.bzl", "al_genquery_write_to_source_file")
        
        al_genquery_write_to_source_file(name, expression, scope, var_name, out_file)
        

        Write genquery result to a bzl file

        Example:

            al_genquery_write_to_source_file(
                name = "al_bzl_libs",
                expression = """
                    filter(
                        "^//",
                        attr(
                            "srcs",
                            ".{3,}",
                            kind(
                                "bzl_library",
                                deps("//bzl")
                            )
                        )
                    )
                """,
                out_file = "al_bzl_libs.bzl",
                scope = ["//bzl"],
                var_name = "AL_BZL_LIBS",
            )
        

        PARAMETERS

        Name Description Default Value
        name name prefix none
        expression genquery expression none
        scope genquery scope none
        var_name variable name in the generated .bzl file none
        out_file output bzl file none

        3.11 - Bzlenv

        Setup bazel environment

        Rules to create a bazel environment which functions similar to venv

        Features

        • Adds bazel-built tools to ${PATH}
        • Exports .env

        Usage

        Create env and activate:

        . "$(bazel run //tools/bzlenv)"
        

        Activate existing env:

        . .bzlenv/bin/activate
        

        Deactivate env:

        bzlenv_deactivate
        

        3.11.1 - Bzl

        Bazel code

        3.11.1.1 - al_bzlenv_binary

        al_bzlenv_binary

        load("@com_alwaldend_src//tools/bzlenv/main/bzl:al_bzlenv_binary.bzl", "al_bzlenv_binary")
        
        al_bzlenv_binary(name, activate, tools)
        

        Dev shell binary

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        activate Activation script Label optional "@com_alwaldend_src//tools/bzlenv/main/sh:activate"
        tools Tools, keys are tool names, values are tool labels Dictionary: String -> Label optional {}

        3.12 - Cc

        Cc

        3.13 - Cloc

        Cloc

        3.14 - Dnscontrol

        Dnscontrol tool

        3.14.1 - Bzl

        Bazel code

        3.14.1.1 - al_dnscontrol_binary

        al_dnscontrol_binary

        load("@com_alwaldend_src//tools/dnscontrol/main/bzl:al_dnscontrol_binary.bzl", "al_dnscontrol_binary")
        
        al_dnscontrol_binary(name, arguments, config, creds, zones)
        

        Dnscontrol binary

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        arguments Dnscontrol arguments List of strings optional []
        config Dnsconfig.js Label required
        creds Creds.json template Label optional None
        zones Zone files List of labels optional []

        3.14.1.2 - al_dnscontrol_test

        al_dnscontrol_test

        load("@com_alwaldend_src//tools/dnscontrol/main/bzl:al_dnscontrol_test.bzl", "al_dnscontrol_test")
        
        al_dnscontrol_test(name, arguments, binary, env_inherit)
        

        Dnscontrol test

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        arguments Dnscontrol arguments List of strings optional []
        binary Dnscontrol binary Label required
        env_inherit Environment variables to inherit List of strings optional []

        3.14.1.3 - al_dnscontrol_toolchain

        al_dnscontrol_toolchain

        load("@com_alwaldend_src//tools/dnscontrol/main/bzl:al_dnscontrol_toolchain.bzl", "al_dnscontrol_toolchain")
        
        al_dnscontrol_toolchain(name, dnscontrol)
        

        Dnscontrol toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        dnscontrol Dnscontrol binary Label required

        3.15 - Docs

        Docs rules

        Usage

        load("//tools/docs:al_docs_files.bzl", "al_docs_files")
        
        al_docs_files(
            name = "docs",
            srcs = glob(["*.md"]),
            prefix = package_name(),
            visibility = ["//:__pkg__"],
        )
        

        3.15.1 - Bzl

        Bazel code

        3.15.1.1 - al_docs_files

        al_docs_files

        load("@com_alwaldend_src//tools/docs/main/bzl:al_docs_files.bzl", "al_docs_files")
        
        al_docs_files(name, visibility, srcs, deps, prefix, root_prefix, renames)
        

        Macro that creates docs files

        PARAMETERS

        Name Description Default Value
        name name none
        visibility visibility none
        srcs docs sources []
        deps other pkg_files rules []
        prefix prefix for pkg_filegroup None
        root_prefix

        -

        "content/docs"
        renames renames for pkg_files {"README.md": "_index.md"}

        3.16 - Drawio

        Bazel rules for drawio

        3.16.1 - Bzl

        Bazel code

        3.16.1.1 - al_drawio_run_binary

        al_drawio_run_binary

        load("@com_alwaldend_src//tools/drawio/main/bzl:al_drawio_run_binary.bzl", "al_drawio_run_binary")
        
        al_drawio_run_binary(name, srcs, out, arguments, cmd_timeout)
        

        Run drawio a a build action

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        srcs Sources List of labels optional []
        out Output Label; nonconfigurable required
        arguments Arguments, location statements are expanded List of strings required
        cmd_timeout Drawio command timeout String optional "1m"

        3.16.1.2 - al_drawio_toolchain

        al_drawio_toolchain

        load("@com_alwaldend_src//tools/drawio/main/bzl:al_drawio_toolchain.bzl", "al_drawio_toolchain")
        
        al_drawio_toolchain(name, drawio)
        

        Drawio toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        drawio Drawio binary Label required

        3.17 - File installer

        CLI tool to install files

        3.18 - Flake8

        Flake8

        3.19 - Git

        Git rules

        3.19.1 - Bzl

        Bazel rules

        3.19.1.1 - al_git_binary

        al_git_binary

        load("@com_alwaldend_src//tools/git/main/bzl:al_git_binary.bzl", "al_git_binary")
        
        al_git_binary(name, arguments)
        

        Run git binary

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        arguments Git arguments (templated) List of strings optional []

        3.19.1.2 - al_git_changelog

        al_git_changelog

        load("@com_alwaldend_src//tools/git/main/bzl:al_git_changelog.bzl", "al_git_changelog")
        
        al_git_changelog(name, visibility, git_binary, subpackages)
        

        Create changelog target

        PARAMETERS

        Name Description Default Value
        name target name prefix none
        visibility visibility none
        git_binary

        -

        "@git//:git"
        subpackages subpackages []

        3.19.1.3 - al_git_current_state

        3.19.1.4 - al_git_extension

        al_git_extension

        al_git_extension = use_extension("@com_alwaldend_src//tools/git/main/bzl:al_git_extension.bzl", "al_git_extension")
        al_git_extension.local_git(name)
        

        Create git repos

        TAG CLASSES

        local_git

        Attributes

        Name Description Type Mandatory Default
        name Name Name required

        3.19.1.5 - al_git_info_file

        al_git_info_file

        load("@com_alwaldend_src//tools/git/main/bzl:al_git_info_file.bzl", "al_git_info_file")
        
        al_git_info_file(name, git_state, git_tool, timeout)
        

        Generate git info file

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        git_state Files that should invalidate the cache on new commit List of labels optional []
        git_tool Git tool to use Label optional "@com_alwaldend_src//tools/git/main/go"
        timeout Timeout in seconds Integer optional 60

        3.19.1.6 - al_git_repo

        al_git_repo

        load("@com_alwaldend_src//tools/git/main/bzl:al_git_repo.bzl", "al_git_repo")
        
        al_git_repo(name, repo_mapping)
        

        Git repo

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this repository. Name required
        repo_mapping In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.

        For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target, it should actually resolve that dependency within globally-declared @bar (@bar//some:target).

        This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension’s implementation function).
        Dictionary: String -> String optional

        3.19.1.7 - al_git_resolved_toolchain

        al_git_resolved_toolchain

        load("@com_alwaldend_src//tools/git/main/bzl:al_git_resolved_toolchain.bzl", "al_git_resolved_toolchain")
        
        al_git_resolved_toolchain(name)
        

        Resolved git toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required

        3.19.1.8 - al_git_run_binary

        al_git_run_binary

        load("@com_alwaldend_src//tools/git/main/bzl:al_git_run_binary.bzl", "al_git_run_binary")
        
        al_git_run_binary(name, srcs, outs, arguments, git)
        

        Run a git binary as a build action

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        srcs Files to be made available List of labels optional []
        outs Outputs List of labels; nonconfigurable required
        arguments Arguments (Location is expanded) List of strings optional []
        git Git binary Label required

        3.19.1.9 - al_git_toolchain

        al_git_toolchain

        load("@com_alwaldend_src//tools/git/main/bzl:al_git_toolchain.bzl", "al_git_toolchain")
        
        al_git_toolchain(name, git_dir, git_path, git_root, invalidation)
        

        Local git toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        git_dir Git directory path String required
        git_path Git binary path String required
        git_root Git workspace path String required
        invalidation Files that should invalidate git actions List of labels optional []

        3.19.2 - Proto

        Protobuf contracts

        3.19.2.1 - contracts

        Proto docs for contracts.proto

        Java

        load("@rules_java//java:defs.bzl", "java_library")
        
        java_library(
            name = "name",
            deps = [
                "@com_alwaldend_src//tools/git/main/proto:contracts_java_library",
            ],
        )
        

        Golang

        load("@rules_go//go:def.bzl", "go_library")
        
        go_library(
            name = "name",
            deps = [
                "@com_alwaldend_src//tools/git/main/proto:proto",
            ],
        )
        

        Proto

        syntax = "proto3";
        
        package git;
        
        option go_package = "git.alwaldend.com/src/tools/git/main/proto/contracts";
        
        message GitSignature {
          string name = 1;
          string email = 2;
          int64 when = 3;
        }
        
        message GitCommit {
          string hash = 1;
          GitSignature author = 2;
          GitSignature committer = 3;
          string merge_tag = 4;
          string pgp_signature = 5;
          string message = 6;
          repeated string tags = 7;
          map<string, bool> changed_files = 8;
        }
        
        message GitTagAnnotated {
          GitSignature tagger = 1;
          string hash = 2;
          string message = 3;
          string pgp_signature = 4;
        }
        
        message GitTag {
          string name = 1;
          string target = 2;
          GitTagAnnotated annotated = 3;
        }
        
        message GitRemote {
          string name = 1;
          repeated string urls = 2;
        }
        
        message GitInfo {
          map<string, GitCommit> commits = 1;
          repeated string commits_order = 2;
          map<string, GitTag> tags = 3;
          repeated GitRemote remotes = 4;
        }
        

        3.20 - Git filter repo

        Git filter repo

        3.21 - Go

        Go rules

        3.21.1 - Bzl

        Bazel code

        3.21.1.1 - al_go_cross_binary

        al_go_cross_binary

        load("@com_alwaldend_src//tools/go/main/bzl:al_go_cross_binary.bzl", "al_go_cross_binary")
        
        al_go_cross_binary(name, target, visibility)
        

        Generate go_cross_binary targets for all valid GOOS_GOARCH and wrap them in a filegroup

        PARAMETERS

        Name Description Default Value
        name name none
        target go_cross_binary target none
        visibility visibility none

        3.21.1.2 - al_go_repository

        al_go_repository

        al_go_repository = use_extension("@com_alwaldend_src//tools/go/main/bzl:al_go_repository.bzl", "al_go_repository")
        al_go_repository.go_repository(name, importpath, sum, version)
        

        Extension wrapper around go_repository (useless because you can just call use_repo_rule)

        TAG CLASSES

        go_repository

        Attributes

        Name Description Type Mandatory Default
        name Name Name required
        importpath importpath String required
        sum checksum String optional ""
        version - String required

        3.22 - Gzip

        Gzip rules

        3.22.1 - Bzl

        Bazel code

        3.22.1.1 - al_gzip_extension

        al_gzip_extension

        al_gzip_extension = use_extension("@com_alwaldend_src//tools/gzip/main/bzl:al_gzip_extension.bzl", "al_gzip_extension")
        al_gzip_extension.download(name, integrity, url)
        

        Extension for gzip repos

        TAG CLASSES

        download

        Attributes

        Name Description Type Mandatory Default
        name Name Name required
        integrity Integrity String optional ""
        url Url String required

        3.22.1.2 - al_gzip_repo

        al_gzip_repo

        load("@com_alwaldend_src//tools/gzip/main/bzl:al_gzip_repo.bzl", "al_gzip_repo")
        
        al_gzip_repo(name, integrity, repo_mapping, url)
        

        Gzip repo

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this repository. Name required
        integrity Integrity String optional ""
        repo_mapping In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.

        For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target, it should actually resolve that dependency within globally-declared @bar (@bar//some:target).

        This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension’s implementation function).
        Dictionary: String -> String optional
        url Url String required

        3.23 - Haskell

        Haskell

        3.24 - Helm

        Bazel rules for helm

        3.24.1 - Bzl

        Bazel code

        3.24.1.1 - al_helm_binary

        al_helm_binary

        load("@com_alwaldend_src//tools/helm/main/bzl:al_helm_binary.bzl", "al_helm_binary")
        
        al_helm_binary(name, data, arguments, cd)
        

        Helm binary

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        data Helm chart List of labels optional []
        arguments Helm arguments List of strings optional []
        cd Cd to a directory before running bazel String optional ""

        3.24.1.2 - al_helm_chart

        al_helm_chart

        load("@com_alwaldend_src//tools/helm/main/bzl:al_helm_chart.bzl", "al_helm_chart")
        
        al_helm_chart(name, deps, package, source)
        

        Helm chart

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        deps Helm chart deps List of labels optional []
        package Helm chart package Label optional None
        source Helm chart source Label optional None

        3.24.1.3 - al_helm_chart_info

        AlHelmChartInfo

        load("@com_alwaldend_src//tools/helm/main/bzl:al_helm_chart_info.bzl", "AlHelmChartInfo")
        
        AlHelmChartInfo(source, package, deps, files_info)
        

        Information about a helm chart

        FIELDS

        Name Description
        source Chart sources (PackageFilegroupInfo, optional)
        package Chart package (tgz file)
        deps Chart deps (depset of AlHelmChartInfo)
        files_info Chart file structure (PackageFilesInfo)

        3.24.1.4 - al_helm_chart_lock

        al_helm_chart_lock

        load("@com_alwaldend_src//tools/helm/main/bzl:al_helm_chart_lock.bzl", "al_helm_chart_lock")
        
        al_helm_chart_lock(name, lock, lock_out)
        

        Generate targets for a chart lock

        PARAMETERS

        Name Description Default Value
        name name none
        lock lock label none
        lock_out parsed lock filename none

        3.24.1.5 - al_helm_cmds

        3.24.1.6 - al_helm_deps

        al_helm_deps

        al_helm_deps = use_extension("@com_alwaldend_src//tools/helm/main/bzl:al_helm_deps.bzl", "al_helm_deps")
        al_helm_deps.from_locks(name, integrity, locks)
        

        Extension to download helm dependencies

        TAG CLASSES

        from_locks

        Attributes

        Name Description Type Mandatory Default
        name Repo name Name required
        integrity Intergrity for locks, keys are packages, values are integrity Dictionary: String -> String optional {}
        locks Helm lock labels List of labels optional []

        3.24.1.7 - al_helm_deps_repo

        al_helm_deps_repo

        load("@com_alwaldend_src//tools/helm/main/bzl:al_helm_deps_repo.bzl", "al_helm_deps_repo")
        
        al_helm_deps_repo(name, integrity, locks, repo_mapping)
        

        Helm deps repo

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this repository. Name required
        integrity Intergrity for locks, keys are packages, values are integrity Dictionary: String -> String optional {}
        locks Lock labels to parse List of labels optional []
        repo_mapping In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.

        For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target, it should actually resolve that dependency within globally-declared @bar (@bar//some:target).

        This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension’s implementation function).
        Dictionary: String -> String optional

        3.24.1.8 - al_helm_toolchain

        al_helm_toolchain

        load("@com_alwaldend_src//tools/helm/main/bzl:al_helm_toolchain.bzl", "al_helm_toolchain")
        
        al_helm_toolchain(name, helm)
        

        Helm toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        helm Helm binary Label required

        3.25 - Hooks

        Git hooks

        3.26 - Http server

        Bazel rules for running http.server

        3.26.1 - Bzl

        Bazel code

        3.26.1.1 - al_http_server_binary

        al_http_server_binary

        load("@com_alwaldend_src//tools/http_server/main/bzl:al_http_server_binary.bzl", "al_http_server_binary")
        
        al_http_server_binary(name, srcs, arguments)
        

        Run a http server

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        srcs Files to symlink List of labels optional []
        arguments Arguments List of strings optional []

        3.27 - Hugo

        Hugo rules

        3.27.1 - Bzl

        Bazel code

        3.27.1.1 - al_hugo_archives

        3.27.1.2 - al_hugo_binary

        al_hugo_binary

        load("@com_alwaldend_src//tools/hugo/main/bzl:al_hugo_binary.bzl", "al_hugo_binary")
        
        al_hugo_binary(name, arguments, site)
        

        Run a hugo command

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        arguments Hugo arguments List of strings optional []
        site Hugo site Label optional None

        3.27.1.3 - al_hugo_extension

        al_hugo_extension

        al_hugo_extension = use_extension("@com_alwaldend_src//tools/hugo/main/bzl:al_hugo_extension.bzl", "al_hugo_extension")
        al_hugo_extension.lock(name, lock)
        al_hugo_extension.toolchains(name, version)
        

        Hugo extension

        TAG CLASSES

        lock

        Attributes

        Name Description Type Mandatory Default
        name Name prefix Name required
        lock Hugo lock path Label required

        toolchains

        Attributes

        Name Description Type Mandatory Default
        name Name Name required
        version Release version String required

        3.27.1.4 - al_hugo_run_binary

        al_hugo_run_binary

        load("@com_alwaldend_src//tools/hugo/main/bzl:al_hugo_run_binary.bzl", "al_hugo_run_binary")
        
        al_hugo_run_binary(name, outs, arguments, hugo, out_dirs)
        

        Run hugo binary as a build action

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        outs Output files List of labels; nonconfigurable optional []
        arguments Hugo arguments List of strings optional []
        hugo Hugo binary to use Label required
        out_dirs Output directories List of strings optional []

        3.27.1.5 - al_hugo_site

        al_hugo_site

        load("@com_alwaldend_src//tools/hugo/main/bzl:al_hugo_site.bzl", "al_hugo_site")
        
        al_hugo_site(name, env, postcss, site, tools)
        

        Define a hugo site

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        env Hugo environment variables (support location statements, support make variables, support shell commands) Dictionary: String -> String optional {}
        postcss Postcss target Label required
        site Hugo site archive Label required
        tools Tools that should be available for the build List of labels optional []

        3.27.1.6 - al_hugo_site_info

        AlHugoSiteInfo

        load("@com_alwaldend_src//tools/hugo/main/bzl:al_hugo_site_info.bzl", "AlHugoSiteInfo")
        
        AlHugoSiteInfo(site_archive, env, env_script)
        

        Information about a hugo site

        FIELDS

        Name Description
        site_archive Site archive File (.tar)
        env Environment variables
        env_script Shell script to export env variables

        3.27.1.7 - al_hugo_toolchain

        al_hugo_toolchain

        load("@com_alwaldend_src//tools/hugo/main/bzl:al_hugo_toolchain.bzl", "al_hugo_toolchain")
        
        al_hugo_toolchain(name, hugo)
        

        Hugo toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        hugo Hugo binary Label required

        3.28 - Install file

        Bazel rules to install files

        3.28.1 - Bzl

        Bazel code

        3.28.1.1 - al_install_file

        al_install_file

        load("@com_alwaldend_src//tools/install_file/main/bzl:al_install_file.bzl", "al_install_file")
        
        al_install_file(name, args, install_file_label, visibility, **py_binary_kwargs)
        

        Create py_binary target to install file

        PARAMETERS

        Name Description Default Value
        name target name none
        args install-file args []
        install_file_label

        -

        "//tools/install_file/main/py:install_file_lib"
        visibility

        -

        ["//:__subpackages__"]
        py_binary_kwargs

        -

        none

        3.29 - Isort

        Isort

        3.30 - Js

        Js

        3.31 - Kt

        Kotlin

        3.32 - License

        License

        3.33 - Lua

        Lua rules

        3.33.1 - Bzl

        Bazel code

        3.33.1.1 - al_lua_library

        al_lua_library

        load("@com_alwaldend_src//tools/lua/main/bzl:al_lua_library.bzl", "al_lua_library")
        
        al_lua_library(name, srcs, check, stylua_config_label, stylua_label, pkg_kwargs, visibility)
        

        Generate targets for a lua library

        PARAMETERS

        Name Description Default Value
        name library name none
        srcs library sources none
        check if set, only these files will be checked []
        stylua_config_label

        -

        "//tools/stylua:stylua_config"
        stylua_label

        -

        "//tools/stylua"
        pkg_kwargs

        -

        {}
        visibility visibility ["//:__subpackages__"]

        3.34 - Make install

        Rules to create tar archives that can be installed with make

        3.34.1 - Bzl

        Bazel code

        3.34.1.1 - al_make_install

        al_make_install

        load("@com_alwaldend_src//tools/make_install/main/bzl:al_make_install.bzl", "al_make_install")
        
        al_make_install(name, srcs)
        

        Create the make install executable and a filegroup

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        srcs Make install filegroups List of labels optional []

        3.34.1.2 - al_make_install_binary

        al_make_install_binary

        load("@com_alwaldend_src//tools/make_install/main/bzl:al_make_install_binary.bzl", "al_make_install_binary")
        
        al_make_install_binary(name, src, arguments)
        

        Create a binary target for a make install

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        src Make install target Label required
        arguments Arugments for the executable List of strings optional []

        3.34.1.3 - al_make_install_filegroup

        al_make_install_filegroup

        load("@com_alwaldend_src//tools/make_install/main/bzl:al_make_install_filegroup.bzl", "al_make_install_filegroup")
        
        al_make_install_filegroup(name, deps, srcs, diff_args, install_args, install_dir, pkg_prefix)
        

        Create a make install filegroup

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        deps Deps List of labels optional []
        srcs Sources to install List of labels optional []
        diff_args Diff args List of strings optional []
        install_args Install args List of strings optional ["--compare", "-D", "--backup=numbered"]
        install_dir Install directory String optional "${HOME}"
        pkg_prefix Ignore that prefix for srcs String required

        3.34.1.4 - al_make_install_filegroup_info

        AlMakeInstallFilegroupInfo

        load("@com_alwaldend_src//tools/make_install/main/bzl:al_make_install_filegroup_info.bzl", "AlMakeInstallFilegroupInfo")
        
        AlMakeInstallFilegroupInfo(srcs, deps, install_dir, origin, install_args, diff_args, pkg_prefix)
        

        Describe install info for a single filegrop

        FIELDS

        Name Description
        srcs depset of PackageFilegroupInfo
        deps depset of AlMakeInstallFilegroupInfo
        install_dir Install directory
        origin Rule label
        install_args Args for the install command
        diff_args Args for the diff command
        pkg_prefix Ignore that prefix for srcs

        3.35 - Md

        Md rules

        3.35.1 - Bzl

        Bazel code

        3.35.1.1 - al_md_data

        al_md_data

        load("@com_alwaldend_src//tools/md/main/bzl:al_md_data.bzl", "al_md_data")
        
        al_md_data(name, srcs, deps, **kwargs)
        

        Markdown data backed by a filegroup

        Targets:

        • ${name}: filegroup

        PARAMETERS

        Name Description Default Value
        name filegroup name none
        srcs markdown files none
        deps deps []
        kwargs filegroup kwargs none

        3.36 - Minisign

        Minisign

        3.36.1 - Bzl

        Bazel code

        3.36.1.1 - al_minisign_archives

        3.36.1.2 - al_minisign_binary

        al_minisign_binary

        load("@com_alwaldend_src//tools/minisign/main/bzl:al_minisign_binary.bzl", "al_minisign_binary")
        
        al_minisign_binary(name)
        

        Minisign binary

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required

        3.36.1.3 - al_minisign_extension

        al_minisign_extension

        al_minisign_extension = use_extension("@com_alwaldend_src//tools/minisign/main/bzl:al_minisign_extension.bzl", "al_minisign_extension")
        al_minisign_extension.repo(name, version)
        

        Minisign extension

        TAG CLASSES

        repo

        Attributes

        Name Description Type Mandatory Default
        name Repo name Name required
        version Minisign version String required

        3.36.1.4 - al_minisign_repo

        al_minisign_repo

        load("@com_alwaldend_src//tools/minisign/main/bzl:al_minisign_repo.bzl", "al_minisign_repo")
        
        al_minisign_repo(name, platform, repo_mapping, version)
        

        Minisign repo

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this repository. Name required
        platform Minisign platform String required
        repo_mapping In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.

        For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target, it should actually resolve that dependency within globally-declared @bar (@bar//some:target).

        This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension’s implementation function).
        Dictionary: String -> String optional
        version Minisign version String required

        3.36.1.5 - al_minisign_toolchain

        al_minisign_toolchain

        load("@com_alwaldend_src//tools/minisign/main/bzl:al_minisign_toolchain.bzl", "al_minisign_toolchain")
        
        al_minisign_toolchain(name, minisign)
        

        Minisign toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        minisign Minisign binary Label required

        3.37 - Mypy

        Mypy

        3.39 - Oci

        Oci

        3.40 - Oras

        Oras rules

        3.40.1 - Bzl

        Bazel code

        3.40.1.1 - al_oras_archives

        3.40.1.2 - al_oras_binary

        al_oras_binary

        load("@com_alwaldend_src//tools/oras/main/bzl:al_oras_binary.bzl", "al_oras_binary")
        
        al_oras_binary(name, arguments)
        

        Oras binary

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        arguments Arguments List of strings optional []

        3.40.1.3 - al_oras_extension

        al_oras_extension

        al_oras_extension = use_extension("@com_alwaldend_src//tools/oras/main/bzl:al_oras_extension.bzl", "al_oras_extension")
        al_oras_extension.toolchains(name, version)
        

        Oras extension

        TAG CLASSES

        toolchains

        Attributes

        Name Description Type Mandatory Default
        name Name Name required
        version Release version String required

        3.40.1.4 - al_oras_toolchain

        al_oras_toolchain

        load("@com_alwaldend_src//tools/oras/main/bzl:al_oras_toolchain.bzl", "al_oras_toolchain")
        
        al_oras_toolchain(name, oras)
        

        oras toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        oras oras binary Label required

        3.41 - Patch

        Patch rules

        3.41.1 - Bzl

        Bazel code

        3.41.1.1 - al_apply_patches

        al_apply_patches

        load("@com_alwaldend_src//tools/patch/main/bzl:al_apply_patches.bzl", "al_apply_patches")
        
        al_apply_patches(name, src, patches, visibility, **kwargs)
        

        Create a genrule applying patches

        PARAMETERS

        Name Description Default Value
        name genrule name none
        src source archive label none
        patches patches label none
        visibility visibility ["//:__subpackages__"]
        kwargs other genrule kwargs none

        3.42 - Pkg

        Package rules

        3.42.1 - Bzl

        Bazel code

        3.42.1.1 - al_genrule_src

        al_genrule_src

        load("@com_alwaldend_src//tools/pkg/main/bzl:al_genrule_src.bzl", "al_genrule_src")
        
        al_genrule_src(name, srcs, visibility)
        

        Create a filegroup and a genrule generating a tar archive

        PARAMETERS

        Name Description Default Value
        name genrule name none
        srcs source labels []
        visibility

        -

        ["//:__subpackages"]

        3.42.1.2 - al_pkg_extract_dir

        al_pkg_extract_dir

        load("@com_alwaldend_src//tools/pkg/main/bzl:al_pkg_extract_dir.bzl", "al_pkg_extract_dir")
        
        al_pkg_extract_dir(name, src, out, arguments)
        

        Extract an archive into a TreeArtifact

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        src Archive to unpack Label required
        out Output directory name String optional ""
        arguments Additional arguments List of strings optional []

        3.42.1.3 - al_pkg_tar_combined

        al_pkg_tar_combined

        load("@com_alwaldend_src//tools/pkg/main/bzl:al_pkg_tar_combined.bzl", "al_pkg_tar_combined")
        
        al_pkg_tar_combined(name, srcs, strip_components, **kwargs)
        

        Create a genrule combining several tars into one

        PARAMETERS

        Name Description Default Value
        name genrule name none
        srcs dicts tar archives ({“label”: “tar label”, “dir”: “target dir”}) []
        strip_components value of –stip-components 2
        kwargs other genrule kwargs none

        3.42.1.4 - al_unpack_archives

        al_unpack_archives

        load("@com_alwaldend_src//tools/pkg/main/bzl:al_unpack_archives.bzl", "al_unpack_archives")
        
        al_unpack_archives(name, srcs, out)
        

        Unpack several archives using tar into a directory

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        srcs - List of labels required
        out - String optional ""

        3.43 - Pl

        Perl

        3.44 - Pnpm

        Pnpm

        3.45 - Postcss

        Postcss

        3.46 - Prettier

        Prettier

        3.47 - Print deps

        Aspect to print deps

        3.47.1 - Bzl

        Bazel code

        3.47.1.1 - al_print_deps

        al_print_deps

        load("@com_alwaldend_src//tools/print_deps/main/bzl:al_print_deps.bzl", "al_print_deps")
        
        al_print_deps()
        

        ASPECT ATTRIBUTES

        Name Type
        deps String

        ATTRIBUTES

        3.48 - Proto

        Protobuf rules

        3.48.1 - Bzl

        Bazel code

        3.48.1.1 - al_proto_docs

        al_proto_docs

        load("@com_alwaldend_src//tools/proto/main/bzl:al_proto_docs.bzl", "al_proto_docs")
        
        al_proto_docs(name, src, prefix, visibility, renames)
        

        Generate protobuf documentation

        PARAMETERS

        Name Description Default Value
        name name none
        src protobuf source file none
        prefix

        -

        None
        visibility visibility None
        renames

        -

        None

        3.49 - Py

        Python rules

        3.49.1 - Bzl

        Bazel code

        3.49.1.1 - al_compile_pip_requirements_combined

        al_compile_pip_requirements_combined

        load("@com_alwaldend_src//tools/py/main/bzl:al_compile_pip_requirements_combined.bzl", "al_compile_pip_requirements_combined")
        
        al_compile_pip_requirements_combined(name, srcs, **kwargs)
        

        Create compile_pip_requirements target for several requirement files

        PARAMETERS

        Name Description Default Value
        name compile_pip_requirements name none
        srcs list of labels of requirement files to combine none
        kwargs kwargs for compile_pip_requirements none

        3.49.1.2 - al_genrule_with_wheels

        al_genrule_with_wheels

        load("@com_alwaldend_src//tools/py/main/bzl:al_genrule_with_wheels.bzl", "al_genrule_with_wheels")
        
        al_genrule_with_wheels(name, wheels, srcs, cmd, **kwargs)
        

        Regular genrule with wheels added to ${PYTHONPATH}

        PARAMETERS

        Name Description Default Value
        name genrule name none
        wheels list of wheel labels none
        srcs srcs for the genrule []
        cmd genrule cmd []
        kwargs other genrule kwargs none

        3.49.1.3 - al_py_binary_shell

        al_py_binary_shell

        load("@com_alwaldend_src//tools/py/main/bzl:al_py_binary_shell.bzl", "al_py_binary_shell")
        
        al_py_binary_shell(name, deps, srcs, shell_type, shell_label, **kwargs)
        

        Create a py_binary target that allows you to run commands in proper python environment

        PARAMETERS

        Name Description Default Value
        name target name none
        deps py_binary deps []
        srcs py_binary srcs []
        shell_type ${BAZEL_PYTHON_SHELL_TYPE} "python"
        shell_label

        -

        "//tools/py/main/py:bazel_python_shell_lib"
        kwargs other py_binary kwargs none

        3.49.1.4 - al_py_checker

        al_py_checker

        load("@com_alwaldend_src//tools/py/main/bzl:al_py_checker.bzl", "al_py_checker")
        
        al_py_checker(name, tool, args_bin, args_test, test_size, disable_fix, **kwargs)
        

        Create -fix and -test targets for a python checker

        PARAMETERS

        Name Description Default Value
        name Name prefix None
        tool Tool label None
        args_bin Args for the binary target None
        args_test Args for the test None
        test_size

        -

        "small"
        disable_fix If set, do not create fix target False
        kwargs Kwargs for both targets none

        3.49.1.5 - al_py_checkers

        al_py_checkers

        load("@com_alwaldend_src//tools/py/main/bzl:al_py_checkers.bzl", "al_py_checkers")
        
        al_py_checkers(name, srcs, isort_label, black_label, mypy_label, flake8_label, pyproject_label)
        

        Generate -fix and -test targets for python checkers

        PARAMETERS

        Name Description Default Value
        name

        -

        none
        srcs list of source file labels none
        isort_label

        -

        "//tools/isort"
        black_label

        -

        "//tools/black"
        mypy_label

        -

        "//tools/mypy"
        flake8_label

        -

        "//tools/flake8"
        pyproject_label

        -

        "//:pyproject"

        3.50 - Qt

        Qt rules

        Qt setup

        • Install qt: aqt install-qt -O /opt/qt linux desktop 6.9.0
        • Register toolchain: register_toolchains("//tools/qt:preinstalled_qt_toolchain")

        3.50.1 - Bzl

        Bazel code

        3.50.1.1 - al_qt_local_toolchain

        al_qt_local_toolchain

        load("@com_alwaldend_src//tools/qt/main/bzl:al_qt_local_toolchain.bzl", "al_qt_local_toolchain")
        
        al_qt_local_toolchain(name, dir, platform, version)
        

        Local qt toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        dir Root qt directory String required
        platform Qt platform String required
        version Qt version String required

        3.50.1.2 - al_qt_resolved_toolchain

        al_qt_resolved_toolchain

        load("@com_alwaldend_src//tools/qt/main/bzl:al_qt_resolved_toolchain.bzl", "al_qt_resolved_toolchain")
        
        al_qt_resolved_toolchain(name)
        

        Resolved qt toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required

        3.51 - Readme tree

        Tool to parse README.md files

        Example

        bazel run tools/readme_tree -- parse -g -C "${PWD}" .
        

        3.52 - Release

        Release rules

        3.52.1 - Bzl

        Bazel bindings for the release tool

        3.52.1.1 - al_release

        al_release

        load("@com_alwaldend_src//tools/release/main/bzl:al_release.bzl", "al_release")
        
        al_release(name, srcs, git_state, manifest, project, release_name, release_tool, root_prefix)
        

        Rule describing a release

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        srcs Sources List of labels optional []
        git_state Files that should invalidate the cache on new commit List of labels optional []
        manifest Load manifest from a file instead of generating it from srcs Label optional None
        project Project package_name String required
        release_name Release name String required
        release_tool Release tool Label optional "@com_alwaldend_src//tools/release/main/go"
        root_prefix Root prefix String optional "content/docs"

        3.52.1.2 - al_release_binary

        al_release_binary

        load("@com_alwaldend_src//tools/release/main/bzl:al_release_binary.bzl", "al_release_binary")
        
        al_release_binary(name, srcs, arguments, cmd, oras, release_tool)
        

        Release binary

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        srcs Releases List of labels optional []
        arguments Arguments List of strings optional []
        cmd Cmd String optional "deploy"
        oras Oras binary Label optional "@com_alwaldend_src//tools/oras"
        release_tool Release tool Label optional "@com_alwaldend_src//tools/release/main/go"

        3.52.1.3 - al_release_deployment

        al_release_deployment

        load("@com_alwaldend_src//tools/release/main/bzl:al_release_deployment.bzl", "al_release_deployment")
        
        al_release_deployment(name, oci_repository)
        

        Deployment info

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        oci_repository OCI repository url String optional ""

        3.52.1.4 - al_release_deployment_info

        AlReleaseDeploymentInfo

        load("@com_alwaldend_src//tools/release/main/bzl:al_release_deployment_info.bzl", "AlReleaseDeploymentInfo")
        
        AlReleaseDeploymentInfo(info, info_file)
        

        Deployment info

        FIELDS

        Name Description
        info Deployment info struct
        info_file Deployment info file

        3.52.1.5 - al_release_deps

        al_release_deps

        load("@com_alwaldend_src//tools/release/main/bzl:al_release_deps.bzl", "al_release_deps")
        
        al_release_deps(name, srcs, visibility, **kwargs)
        

        Generate a dependency diagram using genquery

        PARAMETERS

        Name Description Default Value
        name name none
        srcs list of labels to generate deps for (should be full labels) none
        visibility visibility None
        kwargs kwargs for al_release_files none

        3.52.1.6 - al_release_files

        al_release_files

        load("@com_alwaldend_src//tools/release/main/bzl:al_release_files.bzl", "al_release_files")
        
        al_release_files(name, deps, srcs, deployments, ignore_suffixes, release_tool)
        

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        deps Deps List of labels optional []
        srcs Sources List of labels optional []
        deployments Deployment info List of labels optional []
        ignore_suffixes Ignore src files ending with these suffixes List of strings optional []
        release_tool Release tool Label optional "@com_alwaldend_src//tools/release/main/go"

        3.52.1.7 - al_release_files_info

        AlReleaseFilesInfo

        load("@com_alwaldend_src//tools/release/main/bzl:al_release_files_info.bzl", "AlReleaseFilesInfo")
        
        AlReleaseFilesInfo(files, manifest)
        

        Release files

        FIELDS

        Name Description
        files File dict, keys are filenames, values are Files
        manifest Release manifest for srcs

        3.52.1.8 - al_release_info

        AlReleaseInfo

        load("@com_alwaldend_src//tools/release/main/bzl:al_release_info.bzl", "AlReleaseInfo")
        
        AlReleaseInfo(release_name, project, files, manifest)
        

        Release information

        FIELDS

        Name Description
        release_name Release name (string)
        project Project subdir (string)
        files File dict, keys are filenames, values are Files
        manifest Release manifest (File)

        3.52.2 - Proto

        Protobuf contracts

        3.52.2.1 - contracts

        Proto docs for contracts.proto

        Java

        load("@rules_java//java:defs.bzl", "java_library")
        
        java_library(
            name = "name",
            deps = [
                "@com_alwaldend_src//tools/release/main/proto:contracts_java_library",
            ],
        )
        

        Golang

        load("@rules_go//go:def.bzl", "go_library")
        
        go_library(
            name = "name",
            deps = [
                "@com_alwaldend_src//tools/release/main/proto:proto",
            ],
        )
        

        Proto

        syntax = "proto3";
        
        package release;
        
        import "tools/git/main/proto/contracts.proto";
        
        option go_package = "git.alwaldend.com/src/tools/release/main/proto/contracts";
        
        message ReleaseHash {
          string algo = 1;
          string content = 2;
        }
        
        message ReleaseFile {
          repeated ReleaseHash hashes = 1;
          string name = 2;
          string safe_name = 6;
          string url = 3;
          int64 size = 4;
          string local_path = 5;
        }
        
        message ReleaseItem {
          ReleaseFile file = 1;
          repeated ReleaseDeployment deployments = 2;
        }
        
        message Project {
          string subdir = 1;
          string safe_subdir = 2;
        }
        
        message Git {
          git.GitCommit revision = 1;
          repeated git.GitCommit commits = 2;
        }
        
        message ReleasePageSectionItemAttr {
          string name = 1;
          string content = 2;
        }
        
        message ReleasePageSectionItem {
          string content = 1;
          string content_url = 2;
          repeated ReleasePageSectionItemAttr attrs = 3;
        }
        
        message ReleasePageSection {
          string title = 1;
          repeated ReleasePageSectionItem items = 2;
        }
        
        message ReleasePage {
          repeated ReleasePageSection sections = 1;
        }
        
        message ReleaseDeploymentOci {
          string repository = 1;
          repeated string tags = 2;
        }
        
        message ReleaseDeployment {
          ReleaseDeploymentOci oci = 1;
        }
        
        message Release {
          repeated ReleaseItem items = 1;
          string name = 2;
          Project project = 3;
          Git git = 4;
        }
        

        3.53 - Replace section

        Replace sections of files

        3.54 - Repo map

        Extension to download several versions of a repository depending on a platform

        3.54.1 - Bzl

        Bazel code

        3.54.1.1 - al_repo_map

        al_repo_map

        al_repo_map = use_extension("@com_alwaldend_src//tools/repo_map/main/bzl:al_repo_map.bzl", "al_repo_map")
        al_repo_map.download(name, build_file_content, build_file_native_binary, download_type, executable,
                             repos, strip_prefix)
        

        Extension to create several repos from a map

        TAG CLASSES

        download

        Attributes

        Name Description Type Mandatory Default
        name Name Name required
        build_file_content Build file content String optional ""
        build_file_native_binary Args for a native binary build file Dictionary: String -> String optional {}
        download_type Download type String optional "http_archive"
        executable Field executable for http_file Boolean optional False
        repos Map of repos Dictionary: String -> List of strings required
        strip_prefix Strip prefix String optional ""

        3.55 - Resolved toolchain

        Helper rule to create a resolved toolchain

        3.55.1 - Bzl

        Bazel code

        3.55.1.1 - al_resolved_toolchain

        al_resolved_toolchain

        load("@com_alwaldend_src//tools/resolved_toolchain/main/bzl:al_resolved_toolchain.bzl", "al_resolved_toolchain")
        
        al_resolved_toolchain(toolchain_label, **kwargs)
        

        Create a resolved toolchain

        PARAMETERS

        Name Description Default Value
        toolchain_label

        -

        none
        kwargs rule kwargs none

        RETURNS

        Resolved toolchain rule

        3.56 - Rfc

        Rfc tools

        3.56.1 - Bzl

        Bazel code

        3.56.1.1 - al_rfc_extension

        al_rfc_extension

        al_rfc_extension = use_extension("@com_alwaldend_src//tools/rfc/main/bzl:al_rfc_extension.bzl", "al_rfc_extension")
        al_rfc_extension.download(name, integrity, rfcs)
        

        Rfc extension

        TAG CLASSES

        download

        Attributes

        Name Description Type Mandatory Default
        name Name Name required
        integrity Rfc integrity Dictionary: String -> String optional {}
        rfcs Rfcs List of strings optional []

        3.56.1.2 - al_rfc_repo

        al_rfc_repo

        load("@com_alwaldend_src//tools/rfc/main/bzl:al_rfc_repo.bzl", "al_rfc_repo")
        
        al_rfc_repo(name, integrity, repo_mapping, rfcs, url)
        

        Rfc repository

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this repository. Name required
        integrity Rfc integrity Dictionary: String -> String optional {}
        repo_mapping In WORKSPACE context only: a dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository.

        For example, an entry "@foo": "@bar" declares that, for any time this repository depends on @foo (such as a dependency on @foo//some:target, it should actually resolve that dependency within globally-declared @bar (@bar//some:target).

        This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension’s implementation function).
        Dictionary: String -> String optional
        rfcs Rfcs List of strings optional []
        url Url format String optional "https://www.rfc-editor.org/rfc/{postfix}"

        3.57 - Rs

        Rust

        3.58 - Run tool

        Run tool rules

        3.58.1 - Bzl

        Bazel code

        3.58.1.1 - al_run_tool

        al_run_tool

        load("@com_alwaldend_src//tools/run_tool/main/bzl:al_run_tool.bzl", "al_run_tool")
        
        al_run_tool(name, tool, executable, test, **kwargs)
        

        Generate either native_test, native_binary, or run_binary target

        PARAMETERS

        Name Description Default Value
        name Target name (required) none
        tool Tool label to run (required) none
        executable If True, generate native_binary False
        test If True, generate native_test False
        kwargs kwargs for rules none

        3.59 - Sh

        Shell rules

        3.59.1 - Bzl

        Bazel code

        3.59.1.1 - al_sh_library

        al_sh_library

        load("@com_alwaldend_src//tools/sh/main/bzl:al_sh_library.bzl", "al_sh_library")
        
        al_sh_library(name, shfmt_src, editorconfig_src, shellcheck_src, run_args_src, visibility,
                      test_data, **sh_kwargs)
        

        Create targets for a shell library

        Targets:

        • ${name}.shfmt_fix: executable to run shfmt
        • ${name}.shfmt_test: test whether the script is formatted
        • ${name}.shellcheck_test: shellcheck test

        PARAMETERS

        Name Description Default Value
        name target name none
        shfmt_src

        -

        "//tools/shfmt"
        editorconfig_src

        -

        "//:editorconfig"
        shellcheck_src

        -

        "//tools/shellcheck"
        run_args_src

        -

        "//tools/sh/main/sh:run_args_lib"
        visibility

        -

        ["//:__subpackages__"]
        test_data

        -

        []
        sh_kwargs kwargs for sh targets none

        3.59.1.2 - al_write_script

        al_write_script

        load("@com_alwaldend_src//tools/sh/main/bzl:al_write_script.bzl", "al_write_script")
        
        al_write_script(name, out, content, make_vars, set_flags, shebang)
        

        Write a script and make it executable

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        out Output file Label; nonconfigurable required
        content Script content String required
        make_vars Additional make vars Dictionary: String -> String optional {}
        set_flags Flags to pass to set List of strings optional ["-eu"]
        shebang Sheband to use String optional "#!/usr/bin/env sh"

        3.60 - Shellcheck

        Shellcheck wrapper

        3.60.1 - Bzl

        Bazel code

        3.60.1.1 - al_shellcheck_toolchain

        al_shellcheck_toolchain

        load("@com_alwaldend_src//tools/shellcheck/main/bzl:al_shellcheck_toolchain.bzl", "al_shellcheck_toolchain")
        
        al_shellcheck_toolchain(name, shellcheck)
        

        Shellcheck toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        shellcheck Shellcheck binary Label required

        3.61 - Shfmt

        Shfmt

        3.62 - Stylua

        Stylua wrapper

        3.63 - Taplo

        Taplo

        3.64 - Template files

        Tool and rules to template files

        3.64.1 - Bzl

        Bazel code

        3.64.1.1 - al_template_files

        al_template_files

        load("@com_alwaldend_src//tools/template_files/main/bzl:al_template_files.bzl", "al_template_files")
        
        al_template_files(name, srcs, data, outs, args, templater)
        

        Load data files, then template the template and write the output

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        srcs Template files List of labels required
        data Data files List of labels required
        outs Output files List of labels; nonconfigurable required
        args Extra arguments List of strings optional []
        templater Templater to use Label optional "@com_alwaldend_src//tools/template_files"

        3.65 - Toml

        Toml rules

        3.65.1 - Bzl

        Bazel code

        3.65.1.1 - al_toml_data

        al_toml_data

        load("@com_alwaldend_src//tools/toml/main/bzl:al_toml_data.bzl", "al_toml_data")
        
        al_toml_data(name, deps, srcs, tomlv)
        

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        deps Toml data targets List of labels optional []
        srcs Toml files List of labels optional []
        tomlv Tomlv target to use for validation Label optional "@com_alwaldend_src//tools/tomlv"

        3.65.1.2 - al_toml_info

        AlTomlInfo

        load("@com_alwaldend_src//tools/toml/main/bzl:al_toml_info.bzl", "AlTomlInfo")
        
        AlTomlInfo(srcs, deps)
        

        Provide toml data info

        FIELDS

        Name Description
        srcs Toml files
        deps Toml data targets

        3.65.1.3 - al_toml_validate

        al_toml_validate

        load("@com_alwaldend_src//tools/toml/main/bzl:al_toml_validate.bzl", "al_toml_validate")
        
        al_toml_validate()
        

        Aspect adding linters for toml files

        ASPECT ATTRIBUTES

        Name Type
        deps String

        ATTRIBUTES

        3.66 - Tomlv

        Tomlv

        3.67 - Transitive sources

        Provider and a rule to extract transitive sources

        3.67.1 - Bzl

        Bazel code

        3.67.1.1 - al_transitive_sources

        AlTransitiveSources

        load("@com_alwaldend_src//tools/transitive_sources/main/bzl:al_transitive_sources.bzl", "AlTransitiveSources")
        
        AlTransitiveSources(transitive_sources)
        

        Provide transitive sources

        FIELDS

        Name Description
        transitive_sources -

        al_transitive_sources

        load("@com_alwaldend_src//tools/transitive_sources/main/bzl:al_transitive_sources.bzl", "al_transitive_sources")
        
        al_transitive_sources(srcs, deps)
        

        Obtain the source files for a target and its transitive dependencies.

        PARAMETERS

        Name Description Default Value
        srcs a list of source files none
        deps a list of targets that are direct dependencies none

        RETURNS

        a collection of the transitive sources

        3.68 - Trufflehog

        Trufflehog

        3.68.1 - Bzl

        Bazel code

        3.68.1.1 - al_trufflehog_archives

        3.68.1.2 - al_trufflehog_binary

        al_trufflehog_binary

        load("@com_alwaldend_src//tools/trufflehog/main/bzl:al_trufflehog_binary.bzl", "al_trufflehog_binary")
        
        al_trufflehog_binary(name, arguments)
        

        Trufflehog binary

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        arguments Arguments List of strings optional []

        3.68.1.3 - al_trufflehog_extension

        al_trufflehog_extension

        al_trufflehog_extension = use_extension("@com_alwaldend_src//tools/trufflehog/main/bzl:al_trufflehog_extension.bzl", "al_trufflehog_extension")
        al_trufflehog_extension.toolchains(name, version)
        

        Trufflehog extension

        TAG CLASSES

        toolchains

        Attributes

        Name Description Type Mandatory Default
        name Name Name required
        version Release version String required

        3.68.1.4 - al_trufflehog_test

        al_trufflehog_test

        load("@com_alwaldend_src//tools/trufflehog/main/bzl:al_trufflehog_test.bzl", "al_trufflehog_test")
        
        al_trufflehog_test(name, arguments)
        

        Trufflehog binary

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        arguments Arguments List of strings optional []

        3.68.1.5 - al_trufflehog_toolchain

        al_trufflehog_toolchain

        load("@com_alwaldend_src//tools/trufflehog/main/bzl:al_trufflehog_toolchain.bzl", "al_trufflehog_toolchain")
        
        al_trufflehog_toolchain(name, trufflehog)
        

        Trufflehog toolchain

        ATTRIBUTES

        Name Description Type Mandatory Default
        name A unique name for this target. Name required
        trufflehog Trufflehog binary Label required

        3.69 - Twine

        Twine

        3.70 - Txt

        Text rules

        3.70.1 - Bzl

        Bazel code

        3.70.1.1 - al_combine_files

        al_combine_files

        load("@com_alwaldend_src//tools/txt/main/bzl:al_combine_files.bzl", "al_combine_files")
        
        al_combine_files(name, srcs, **kwargs)
        

        Create a genrule combining several files into one

        PARAMETERS

        Name Description Default Value
        name genrule target none
        srcs list of labels to combine none
        kwargs other genrule kwargs none

        3.70.1.2 - al_txt_data

        al_txt_data

        load("@com_alwaldend_src//tools/txt/main/bzl:al_txt_data.bzl", "al_txt_data")
        
        al_txt_data(name, srcs, **kwargs)
        

        Text data

        PARAMETERS

        Name Description Default Value
        name target name none
        srcs sources none
        kwargs filegroup kwargs none

        3.71 - Vial

        Bazel rules for Vial

        3.71.1 - Bzl

        Bazel code

        3.71.1.1 - al_vial_configs

        al_vial_configs

        load("@com_alwaldend_src//tools/vial/main/bzl:al_vial_configs.bzl", "al_vial_configs")
        
        al_vial_configs(name, srcs, visibility, **kwargs)
        

        Generate vial config targets

        PARAMETERS

        Name Description Default Value
        name generated docs archive name none
        srcs vial config none
        visibility visibility None
        kwargs kwargs for al_template_files none

        3.72 - Workspace status

        Workspace status script

        4 - Misc

        Miscellaneous pages

        4.1 - Android

        Android

        Diagnostics

        Android has some built-in tests for the display and other components in Settings -> System -> Device diagnostics

        4.2 - Bazel

        Advantages

        • Hermetic builds
        • Dependency graph
        • Local build and test cache
        • Remote cache
        • Remote execution
        • Unified API for builds, tasks, and tests

        Disadvantages

        • Additional layer of abstraction and complexity
        • Weird edge cases and occasional bugs
        • Lack of support, documentation, and information on the internet
        • The majority of advantages are irrelevant for the majority of codebases

        .bazelrc has variables

        • %workspace%: Workspace directory

        https://bazel.build/run/bazelrc

        Local registry module is cached

        If you changed a local registry module, but bazel still uses the old version, restart bazel: bazel shutdown

        https://github.com/bazelbuild/bazel/issues/20477#issuecomment-1851057077

        Output root ownership

        Bazel checks ownership of the output root at startup, so it will fail with mkdir('/path/to/dir'): (error: 13): Permission denied if the current user does not own the directory.

        Example:

        $ bazel --client_debug
        ...
        [FATAL 15:19:33.457 src/main/cpp/blaze_util_posix.cc:499] mkdir('/path/to/dir'): (error: 13): Permission denied
        

        Traceback:

        js_binary does not work for some reason

        One of possible errors:

        FATAL: aspect_rules_js[js_binary]: RUNFILES environment variable is not set
        

        Solutions

        Run the binary (that fixes it for some reason)

        bazel run //tools:postcss
        

        Run pnpm install (sometimes node_modules directory is not up-to-date)

        bazel run -- tools:pnpm --dir "${PWD}" install
        

        4.3 - Books

        Books
        Thumbnail Title
        Sky Pride
        Quality Good, edgy start
        Authors Warby Picus
        Reading Reading, B3C25
        Links royalroad , royalroad (author)
        Thumbnail Title
        Grotesqueries of the Old Domain
        (旧域怪诞) (The Grotesque Old Domain)
        Quality Good?
        Authors Foxtail Quill (狐尾的笔)
        Reading Reading, C65
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        Pale Lights
        Quality Good
        Authors ErraticErrata
        Reading Reading, V3C35
        Links royalroad , royalroad (author)
        Thumbnail Title
        Hell Difficulty Tutorial
        Quality Decent
        Authors Cerim
        Reading Reading, chapter 589
        Links royalroad
        Thumbnail Title
        Book Of The Dead
        Quality Decent
        Authors RinoZ
        Reading Reading, book 5 chapter 25
        Links royalroad , royalroad (author)
        Thumbnail Title
        Shadow Slave
        Quality Decent
        Authors Guiltythree
        Reading Reading, chapter 2388
        Links webnovel , novelbin
        Thumbnail Title
        The Tower of Infinite Evil
        Quality Decent
        Authors Lit Homunculus
        Reading Reading, C93
        Links royalroad , royalroad (author)
        Thumbnail Title
        The Legend of William Oh
        Quality Decent
        Authors Macronomicon
        Reading Reading, C198
        Links royalroad , royalroad (author)
        Thumbnail Title
        Changeling
        Quality Decent
        Authors Mecanimus
        Reading Reading, C83
        Links royalroad
        Thumbnail Title
        Struggling to Survive with Regression Power in the Primordial Saint Sect
        (苟在初圣魔门当人材) (Lying Low as the First Saint Demonic Sect’s ‘Top Talent’)
        Quality Decent
        Authors Crane by the Moonlit Pond (鹤守月满池)
        Reading Dropped, C259
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        For the Glory of Rome
        Quality Ok
        Authors zaifyr
        Reading Dropped, V3C12
        Links royalroad , royalroad (author)
        Thumbnail Title
        Throne Hunters
        Quality Ok
        Authors Phill Tucker
        Reading Dropped, V1C44
        Links royalroad , royalroad (author)
        Thumbnail Title
        Young Master’s PoV: Woke Up As A Villain In A Game One Day
        Quality Ok
        Authors The_One_Who_Was
        Reading Dropped, C293
        Links webnovel , webnovel (author)
        Thumbnail Title
        Unsong
        Quality Good, disgusting ending
        Authors Scott Alexander
        Reading Finished
        Links site , goodreads (author)
        Thumbnail Title
        A Gamer’s Guide To Beating The Tutorial
        Quality Ok
        Authors
        Reading Dropped, C352
        Links royalroad
        Thumbnail Title
        Are You Even Human
        Quality Decent
        Authors Thundamoo
        Reading Dropped, C54
        Links royalroad
        Thumbnail Title
        The Crazy Knight’s Age of the Universe
        (疯骑士的宇宙时代)
        Quality Ok, lost the vibe of the first book
        Authors Angry Squirrel (愤怒的松鼠)
        Reading Dropped, C167
        Links wtr-lab
        Thumbnail Title
        Diary of a Dead Wizard
        (死亡巫师日记)
        Quality Good
        Authors Jin Nai (今奈)
        Reading Finished, C1037
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        Shrouded Seascape
        (诡秘地海)
        Quality Good
        Authors Foxtail Quill (狐尾的笔)
        Reading Finished, C1149
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        Salvage System
        Quality Slop
        Authors Nicholas Sansbury Smith
        Reading Dropped, V1C11
        Links aethonbooks , aethonbooks (author)
        Thumbnail Title
        Mage Tank
        Quality Slop
        Authors Cornman
        Reading Dropped, V1C50
        Links royalroad , royalroad (author)
        Thumbnail Title
        Nightmare Realm Summoner
        Quality Ok
        Authors Actus
        Reading Dropped, C278
        Links royalroad
        Thumbnail Title
        All the Dust that Falls
        Quality Ok
        Authors zaifyr
        Reading Finished, V4
        Links royalroad , royalroad (author)
        Thumbnail Title
        Dear Spellbook
        Quality Ok
        Authors TK523
        Reading Dropped, V3C13
        Links royalroad , royalroad (author)
        Thumbnail Title
        I Became The Necromancer Of The Academy
        Quality Slop
        Authors _172
        Reading Dropped, C37
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        The Shards of Etherious
        Quality Bad
        Authors Colin J.D. Crooks
        Reading Dropped, V1C9
        Links goodreads , goodreads (author)
        Thumbnail Title
        Etherious
        Quality Ok
        Authors EmEs
        Reading Dropped, finished V4
        Links royalroad , royalroad (author)
        Thumbnail Title
        Only at the Mahayana Stage Does the Reversal System Appear
        Quality Ok, bad translation
        Authors The Whitest Crow (最白的乌鸦)
        Reading Dropped, C164
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        New Life As A Max Level Archmage
        Quality Ok
        Authors ArcaneCadence
        Reading Dropped, C44
        Links royalroad , royalroad (author)
        Thumbnail Title
        I Just Want to Slack Off in Cultivation
        (我只想安静的做个苟道中人)
        Quality Slop
        Authors Exploding Small Latte (爆炸小拿铁)
        Reading Dropped, C54
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        Kill the Sun
        Quality Decent
        Authors Warmaisach
        Reading Finished, C992
        Links webnovel , webnovel (author)
        Thumbnail Title
        The System is Abstract, Luckily, So Am I
        Quality Slop
        Authors Pū jiē tiānxiàn (扑街天线)
        Reading Dropped, C311
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        Theos
        Quality Decent
        Authors Arthur Wordsmith
        Reading Hiatus, B3C4
        Links royalroad , royalroad (author)
        Thumbnail Title
        Saving the school would have been easier as a cafeteria worker
        Quality Decent
        Authors CluelessRR
        Reading Dropped, chapter 87
        Links royalroad , royalroad (author)
        Thumbnail Title
        1% Lifesteal
        Quality Ok, boring protagonist
        Authors Robert Blaise
        Reading Dropped, C128 (volume 2)
        Links royalroad
        Thumbnail Title
        Versatile Mage
        (全职法师)
        Quality Slop
        Authors Chaos (乱)
        Reading Dropped, chapter 8
        Links novelupdates
        Thumbnail Title
        Why Are the Talismans I Drawn Banned Again?!
        (我画的符箓必被禁用)
        Quality Slop, rushed ending
        Authors Quiet Support (安静捧场)
        Reading Finshed, chapter 258
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        Dungeon Inspector
        Quality Ok, mediocre
        Authors Flossindune
        Reading Dropped, finished volume 1
        Links royalroad , royalorad (author)
        Thumbnail Title
        The Perfect Run
        Quality Decent
        Authors Maxime J. Durand
        Reading Finished
        Links royalroad , royalroad (author)
        Thumbnail Title
        Blood & Fur
        Quality Good
        Authors Maxime J. Durand
        Reading Finished
        Links royalroad , royalroad (author)
        Thumbnail Title
        Dao of the Bizarre Immortal
        (道诡异仙)
        Quality Decent
        Authors Foxtail Quill (狐尾的笔)
        Reading Finished
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        Cultivation Chat Group
        (修真聊天群)
        Quality Decent
        Authors Legend of the Paladin (圣骑士的传说)
        Reading Finished
        Links novelupdates
        Thumbnail Title
        The Strongest System
        (最强的系统)
        Quality Ok
        Summary Shallow
        Authors Xin Feng (新丰)
        Reading Dropped, chapter 113
        Links novelupdates
        Thumbnail Title
        Solo Leveling
        (我独自升级)
        Quality Ok
        Summary Shallow litrpg slop
        Authors Chugong (추공)
        Reading Dropped, chapter 52
        Links novelupdates
        Thumbnail Title
        I Shall Be Everlasting In the World of Immortals
        (我在修仙界万古长青)
        Quality Ok
        Summary Shallow
        Authors Fast Food Restaurant (快餐店)
        Reading Dropped, chapter 241
        Links novelupdates
        Thumbnail Title
        The Stubborn Skill-Grinder In A Time Loop
        Quality Ok
        Summary Shallow litrpg slop
        Authors X-RHODEN-X
        Reading Dropped, chapter 44
        Links royalroad
        Thumbnail Title
        Unbound
        Quality Ok
        Summary Shallow
        Authors Necariin
        Reading Dropped, finisehd volume 3
        Links royalroad , royalroad (author)
        Thumbnail Title
        The Spiritual Attainment of Minghe
        (明和的精神境界)
        Quality Ok
        Summary Shallow, bad translation
        Authors God Loves The World (神仙爱凡尘)
        Reading Dropped, chapter 8
        Links novelupdates
        Thumbnail Title
        My House of Horrors
        (我有一座冒险屋)
        Quality Ok
        Summary Repetitive
        Authors Can Fix Air-Conditioners (我会修空调)
        Reading Dropped at some point
        Links novelupdates
        Thumbnail Title
        Chrysalis
        Quality Ok
        Authors RinoZ
        Reading Dropped, C1654
        Links royalroad , royalroad (author)
        Thumbnail Title
        Rune Seeker
        Quality Ok
        Summary Shallow
        Authors J.M. Clarke (U Juggernaut)
        Reading Dropped, volume 2, chapter 12
        Links royalroad
        Thumbnail Title
        The Empty Box and Zeroth Maria
        (Utsuro no Hako to Zero no Maria) (空ろの箱と零のマリア)
        Quality Decent?
        Summary Don't remember
        Authors Mikage Eiji
        Reading Finished
        Links novelupdates
        Thumbnail Title
        Forty Millenniums of Cultivation
        (Forty Thousand Years Of Cultivation) (修真四万年)
        Quality 0.8
        Summary Good worldbuilding, but too many empty exclamations and not enough substance
        Authors The Enlightened Master Crouching Cow (卧牛真人)
        Reading Dropped, chapter 2935
        Links novelupdates
        Thumbnail Title
        Trash of the Count’s Family
        Quality Bad
        Summary Korean slop, the same stuff happens over and over again, endless saving of useless garbage, humble bragging
        Authors Yu Ryeo Han (유려한)
        Reading Dropped, chapter 215
        Links novelupdates
        Thumbnail Title
        Perfect World
        Quality Don't remember, children are boring
        Authors Chen Dong (辰东)
        Reading Dropped, chapter 75
        Links novelupdates
        Thumbnail Title
        Warlock of the Magus World
        Quality Bad, edgy slop, too much 'AI chip, do the thing'
        Authors The Plagiarist
        Reading Dropped, chapter 58
        Links novelupdates
        Thumbnail Title
        Shen Yin Wang Zuo
        (Sealed Divine Throne) (神印王座)
        Quality Bad, too bland
        Authors Tang Jia San Shao (唐家三少)
        Reading Dropped, chapter 101
        Links novelupdates
        Thumbnail Title
        Corpo Age
        Quality Ok, feels basic
        Authors RandomBlueCat
        Reading Dropped, volume 1, chapter 2
        Links royalroad
        Thumbnail Title
        SSS-Class Suicide Hunter
        Quality Ok, too much emotional bullshit
        Authors Sinnoa
        Reading Dropped at some point
        Links novelupdates
        Thumbnail Title
        The Divine Dungeon
        Quality Ok, a bit basic
        Authors Dakota Krout
        Reading Finished
        Links goodreads
        Thumbnail Title
        Full Murderhobo
        Quality Ok, a bit basic
        Authors Dakota Krout
        Reading Finished, volume 3
        Links goodreads
        Thumbnail Title
        Worm
        Quality Decent
        Authors Wildbow
        Reading Finished
        Links website
        Thumbnail Title
        12 Miles Below
        Quality Decent
        Authors Mark Arrows
        Reading Dropped at some point
        Links royalroad
        Thumbnail Title
        The Charm of Soul Pets
        Quality Don't remember
        Authors Chaos (乱)
        Reading Dropped, chapter 42
        Links novelupdates
        Thumbnail Title
        Throne of Magical Arcana
        Quality Decent, a bit mediocre
        Authors Cuttlefish That Loves Diving (爱潜水的乌贼)
        Reading Dropped near the end when the main plot ended
        Links novelupdates
        Thumbnail Title
        The Jester of Apocalypse
        Quality Ok, basic and a bit edgy
        Authors Robert Blaise
        Reading Finished available chapters
        Links royalroad
        Thumbnail Title
        Accel World
        Quality Bad, japanese slop
        Authors Kawahara Reki
        Reading Dropped at some point
        Links novelupdates
        Thumbnail Title
        Reborn as a Demonic Tree
        Quality Ok, mediocre
        Authors XKARNATION
        Reading Dropped, volume 8, chapter 421
        Links royalroad
        Thumbnail Title
        System Breaker
        Quality Decent, MC is a bit immature
        Authors
        Reading Dropped, volume 2, chapter 55
        Links royalroad
        Thumbnail Title
        DIE. RESPAWN. REPEAT.
        Quality Decent, a bit bland
        Authors SilverLinings
        Reading Dropped, volume 4, chapter 8 (chapter 222)
        Links royalroad
        Thumbnail Title
        Mark of the Fool
        Quality Decent, not enough progression
        Authors J.M. Clarke (U Juggernaut)
        Reading Finished
        Links royalroad
        Thumbnail Title
        If It’s for My Daughter, I’d Even Defeat a Demon Lord
        Quality Bad, Japanese slice-of-life litrpg fantasy slop
        Authors Chirolu
        Reading Dropped, V4C2
        Links novelupdates
        Thumbnail Title
        Ultimate Level 1
        Quality Bad, litrpg slop
        Authors Dads Bedtime Stories
        Reading Dropped, V1C17
        Links royalroad
        Thumbnail Title
        Vigor Mortis
        Quality Ok
        Authors Thundamoo
        Reading Dropped, V4C27
        Links royalroad
        Thumbnail Title
        Rise of the Living Forge
        Quality Ok
        Authors Actus
        Reading Dropped, C509
        Links royalroad
        Thumbnail Title
        The Beginning After the End
        Quality Bad, isekai slop
        Authors TurtleMe
        Reading Dropped, volume 1, chapter 13
        Links wikipedia
        Thumbnail Title
        Ghost of the Truthseeker
        Quality Ok
        Authors Strungbound
        Reading Dropped, chapter 220
        Links royalroad
        Thumbnail Title
        I Am Become Death
        Quality Decent
        Summary Nothing exceptional
        Authors J.M. Clarke (U Juggernaut)
        Reading Dropped, chapter 55
        Links royalroard
        Thumbnail Title
        Return of the Runebound Professor
        Quality Ok
        Authors Actus
        Reading Reading, B7C749
        Links royalroad
        Thumbnail Title
        World of Cultivation
        (修真世界)
        Quality Good
        Authors Fang Xiang (方想)
        Reading Finished
        Links novelupdates
        Thumbnail Title
        I Shall Seal the Heavens
        Quality Good
        Authors Er Gen (耳根)
        Reading Finished
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        Beware Of Chicken
        Quality Good
        Authors Casualfarmer
        Reading Dropped at some point
        Links royalroad
        Thumbnail Title
        Dungeon Crawler Carl
        Quality Good
        Authors DoctorHepa
        Reading Finished available, B7
        Links royalroad
        Thumbnail Title
        A Practical Guide to Sorcery
        Quality Decent, slow upload
        Authors Azalea Ellis
        Reading Dropped, C262
        Links azaleaellis
        Thumbnail Title
        Downtown Druid
        Quality Decent
        Authors seersucker
        Reading Finished volume 1
        Links royalroad
        Thumbnail Title
        The Years of Apocalypse
        Quality Decent
        Authors UraniumPhoenix
        Reading Dropped, C225
        Links royalroad
        Thumbnail Title
        Renegade Immortal
        Quality Good
        Authors Er Gen (耳根)
        Reading Finished
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        Matabar
        Quality Good
        Authors Kirill Klevanski
        Reading Dropped, chapter 120
        Links royalroad
        Thumbnail Title
        Defiance of the Fall
        Quality Decent
        Authors TheFirstDefier
        Reading Dropped, C1370
        Links royalroad
        Thumbnail Title
        Godclads
        Quality Good, a bit too dramatic
        Authors OstensibleMammal
        Reading Dropped, C37-11
        Links royalroad , royalroad (author)
        Thumbnail Title
        Archfiend
        (最强妖孽)
        Quality Decent
        Authors Nocturnal Stranger (厄夜怪客)
        Reading Finished translated chapters, chapter 528
        Links novelupdates
        Thumbnail Title
        Outside of time
        (光阴之外)
        Quality Ok
        Authors Er Gen (耳根)
        Reading Dropped, C1470
        Links novelupdates , novelupdates (author)
        Thumbnail Title
        The Sage Who Transcended Samsara
        (一世之尊)
        Quality Good
        Authors Cuttlefish That Loves Diving (爱潜水的乌贼)
        Reading Finished, dropped at the end
        Links novelupdates
        Thumbnail Title
        The Experimental Log of the Crazy Lich
        (疯巫妖的实验日志)
        Quality Good
        Authors Angry Squirrel (愤怒的松鼠)
        Reading Finished volume 1
        Links novelupdates
        Thumbnail Title
        Nightfall
        (Ever Night) (将夜)
        Quality Good
        Authors Mao Ni (猫腻)
        Reading Finished
        Links novelupdates
        Thumbnail Title
        The Path Toward Heaven
        (大道朝天)
        Quality Good
        Authors Mao Ni (猫腻)
        Reading Finished available chapters
        Links novelupdates
        Thumbnail Title
        Ze Tian Ji
        (Way of Choices) (择天记)
        Quality Good
        Authors Mao Ni (猫腻)
        Reading Finished
        Links novelupdates
        Thumbnail Title
        Lord of the Mysteries
        Quality Good
        Authors Cuttlefish That Loves Diving (爱潜水的乌贼)
        Reading Finished volume 2
        Links novelupdates
        Thumbnail Title
        Unintended Immortality
        (The Unintentional Path to Immortality) (我本无意成仙)
        Quality Good
        Authors Golden Jasmine (金色茉莉花)
        Reading Finished, C713
        Links novelupdates , novelfile
        Thumbnail Title
        My Longevity Simulation
        Quality Good
        Authors Angry Squid (愤怒的乌贼)
        Reading Dropped, C838
        Links novelupdates , novelbin
        Thumbnail Title
        Virtuous Sons
        Quality Peak
        Authors Ya Boy
        Reading Hiatus, C2.22
        Links royalroad , royalroad (author)
        Thumbnail Title
        Reverend Insanity
        (Gu Daoist Master) (蛊真人)
        Quality Peak
        Authors Gu Zhen Ren (蛊真人)
        Reading Finished available, C2334
        Links novelupdates

        4.4 - Glossary

        Subresource Integrity

        Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.

        https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity

        4.5 - Gnome boxes

        Gnome boxes is a hypervisor.

        Cpu

        The default cpu doesn’t have a lot of capabilities, so you might need to patch the config:

          <!-- https://www.qemu.org/docs/master/system/i386/cpu.html -->
          <cpu mode="host-model" />
        

        Network

        Default libvirt network interferes with gnome-boxes, you might need to disable it:

        sudo systemctl disable --now libvirtd
        

        Disk size

        Just increasing the disk size is not enough, you need to increase the logical volume size:

        sudo growpart /dev/vda 3
        sudo lvextend -l +100%FREE /dev/fedora/root
        sudo xfs_growfs /dev/fedora/root
        

        Links:

        4.6 - Hugo

        Hugo is a static site builder

        Environment variables

        Hugo has an allowlist of environment variables, and js_binary rules do not work because they need a BAZEL_BINDIR variable

        Fix:

        [security.exec]
        osEnv = [
            '(?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|SYSTEMDRIVE|BAZEL.+)$',
        ]
        

        Configuration reference: https://gohugo.io/configuration/security/

        4.7 - Leetcode submissions

        Leetcode submissions

        4.7.1 - 2025-09-22 19:34:44 +0300 MSK

        Count Elements With Maximum Frequency

        Code

        class Solution:
            def maxFrequencyElements(self, nums: List[int]) -> int:
                max_freq, max_freq_count = 0, 0
                freqs = [0] * 101
                for num in nums:
                    freqs[num] += 1
                for num, freq in enumerate(freqs):
                    if freq > max_freq:
                        max_freq, max_freq_count = freq, freq
                    elif freq == max_freq:
                        max_freq_count += freq
                return max_freq_count
        

        4.7.2 - 2025-09-21 19:30:58 +0300 MSK

        Design Movie Rental System

        Code

        class MovieRentingSystem:
        
            def __init__(self, n: int, entries: List[List[int]]):
                self.available = {}  # (shop, movie) -> price
                self.movie_shops = {}  # movie -> list of (price, shop)
                self.rented = set()  # (shop, movie) that are currently rented
        
                for shop, movie, price in entries:
                    self.available[(shop, movie)] = price
                    if movie not in self.movie_shops:
                        self.movie_shops[movie] = []
                    self.movie_shops[movie].append((price, shop))
        
                # Sort shops by price for each movie initially
                for movie in self.movie_shops:
                    self.movie_shops[movie].sort()
        
            def search(self, movie: int) -> List[int]:
                result = []
                for price, shop in self.movie_shops.get(movie, []):
                    if (shop, movie) not in self.rented:
                        result.append(shop)
                    if len(result) == 5:
                        break
                return result
        
            def rent(self, shop: int, movie: int) -> None:
                self.rented.add((shop, movie))
        
            def drop(self, shop: int, movie: int) -> None:
                self.rented.discard((shop, movie))
        
            def report(self) -> List[List[int]]:
                rented_list = []
                for shop, movie in self.rented:
                    price = self.available[(shop, movie)]
                    rented_list.append((price, shop, movie))
        
                rented_list.sort()
                return [[shop, movie] for price, shop, movie in rented_list[:5]]
        

        4.7.3 - 2025-09-20 19:25:16 +0300 MSK

        Implement Router

        Code

        class Router:
            def __init__(self, memoryLimit: int):
                self.size = memoryLimit
                self.packets = {}  # key -> [source, destination, timestamp]
                self.counts = defaultdict(list)  # destination -> sorted list of timestamps
                self.queue = deque()  # FIFO order of packets
        
            def addPacket(self, source: int, destination: int, timestamp: int) -> bool:
                key = self._encode(source, destination, timestamp)
        
                # Duplicate check
                if key in self.packets:
                    return False
        
                # If memory full, forward oldest packet
                if len(self.packets) >= self.size:
                    self.forwardPacket()
        
                # Add packet
                self.packets[key] = [source, destination, timestamp]
                self.queue.append(key)
                self.counts[destination].append(timestamp)
        
                return True
        
            def forwardPacket(self):
                if not self.packets:
                    return []
        
                key = self.queue.popleft()
                packet = self.packets.pop(key)
        
                dest = packet[1]
                self.counts[dest].pop(0)  # remove the earliest timestamp
        
                return packet
        
            def getCount(self, destination: int, startTime: int, endTime: int) -> int:
                timestamps = self.counts.get(destination, [])
                if not timestamps:
                    return 0
        
                # Binary search for range
                left = bisect.bisect_left(timestamps, startTime)
                right = bisect.bisect_right(timestamps, endTime)
        
                return right - left
        
            def _encode(self, source: int, destination: int, timestamp: int) -> int:
                # Encode uniquely into 1 number
                return (source << 40) | (destination << 20) | timestamp
        

        4.7.4 - 2025-09-19 18:44:46 +0300 MSK

        Design Spreadsheet

        Code

        class Spreadsheet:
        
            def __init__(self, rows: int):
                self._grid = [[0] * 26 for _ in range(rows)]
        
            def _coord(self, cell: str) -> tuple[int, int]:
                return int(cell[1:]) - 1, ord(cell[0]) - ord("A")
        
            def setCell(self, cell: str, value: int) -> None:
                row, col = self._coord(cell)
                self._grid[row][col] = value
        
            def resetCell(self, cell: str) -> None:
                row, col = self._coord(cell)
                self._grid[row][col] = 0
        
            def getValue(self, formula: str) -> int:
                res = 0
                for cell in formula[1:].split("+"):
                    if cell[0].isdigit():
                        res += int(cell)
                    else:
                        row, col = self._coord(cell)
                        res += self._grid[row][col]
                return res
        
        # Your Spreadsheet object will be instantiated and called as such:
        # obj = Spreadsheet(rows)
        # obj.setCell(cell,value)
        # obj.resetCell(cell)
        # param_3 = obj.getValue(formula)
        

        4.7.5 - 2025-09-18 19:58:25 +0300 MSK

        Design Task Manager

        Code

        class TaskManager:
            def __init__(self, tasks: List[List[int]]):
                self.tasks = SortedSet()
                self.task_to_users = {}
                self.task_to_priority = {}
                for user_id, task_id, priority in tasks:
                    self.add(user_id, task_id, priority)
            def add(self, userId: int, taskId: int, priority: int) -> None:
                self.tasks.add((priority, taskId, userId))
                self.task_to_users[taskId] = userId
                self.task_to_priority[taskId] = priority
            def edit(self, taskId: int, newPriority: int) -> None:
                user = self.task_to_users[taskId]
                self.rmv(taskId)
                self.add(user, taskId, newPriority)        
            def rmv(self, taskId: int) -> None:
                user = self.task_to_users[taskId]        
                priority = self.task_to_priority[taskId]
                self.tasks.remove((priority, taskId, user))
                del self.task_to_users[taskId]
                del self.task_to_priority[taskId]
            def execTop(self) -> int:
                if not self.tasks:
                    return -1
                _, task_id, user_id = self.tasks[-1]
                self.rmv(task_id)
                return user_id
        

        4.7.6 - 2025-09-17 20:39:54 +0300 MSK

        Design a Food Rating System

        Code

        from sortedcontainers import SortedSet
        
        class FoodRatings:
            def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
                # Map food with its rating.
                self.food_rating_map = {}
                # Map food with the cuisine it belongs to.
                self.food_cuisine_map = {}
        
                # Store all food of cuisine in a set (to sort them on ratings/name)
                # Set element -> Tuple: (-1 * food_rating, food_name)
                self.cuisine_food_map = defaultdict(SortedSet)
        
                for i in range(len(foods)):
                    # Store 'rating' and 'cuisine' of the current 'food' in 'food_rating_map' and 'food_cuisine_map' maps.
                    self.food_rating_map[foods[i]] = ratings[i]
                    self.food_cuisine_map[foods[i]] = cuisines[i]
                    # Insert the '(-1 * rating, name)' element in the current cuisine's set.
                    self.cuisine_food_map[cuisines[i]].add((-ratings[i], foods[i]))
        
            def changeRating(self, food: str, newRating: int) -> None:
                # Fetch cuisine name for food.
                cuisine_name = self.food_cuisine_map[food]
        
                # Find and delete the element from the respective cuisine's set.
                old_element = (-self.food_rating_map[food], food)
                self.cuisine_food_map[cuisine_name].remove(old_element)
        
                # Update food's rating in 'food_rating' map.
                self.food_rating_map[food] = newRating
                # Insert the '(-1 * new rating, name)' element in the respective cuisine's set.
                self.cuisine_food_map[cuisine_name].add((-newRating, food))
        
            def highestRated(self, cuisine: str) -> str:
                highest_rated = self.cuisine_food_map[cuisine][0]
                # Return name of the highest-rated 'food' of 'cuisine'.
                return highest_rated[1]
        

        4.7.7 - 2025-09-16 18:41:40 +0300 MSK

        Replace Non-Coprime Numbers in Array

        Code

        from math import gcd
        
        class Solution(object):
            def replaceNonCoprimes(self, nums):
                stack = []
        
                for num in nums:
                    while stack:
                        g = gcd(stack[-1], num)
                        if g == 1:
                            break
                        num = (stack.pop() * num) // g
                    stack.append(num)
        
                return stack
        

        4.7.8 - 2025-09-15 18:04:52 +0300 MSK

        Maximum Number of Words You Can Type

        Code

        class Solution:
            def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
                ignore = False
                res = 0
                for char in itertools.chain(text, " "):
                    if char == " ":
                        if ignore:
                            ignore = False
                        else:
                            res += 1
                    elif char in brokenLetters:
                        ignore = True
                return res
        

        4.7.9 - 2025-09-14 19:11:43 +0300 MSK

        Vowel Spellchecker

        Code

        class Solution(object):
            def spellchecker(self, wordlist, queries):
                def devowel(word):
                    return "".join('*' if c in 'aeiou' else c
                                   for c in word)
        
                words_perfect = set(wordlist)
                words_cap = {}
                words_vow = {}
        
                for word in wordlist:
                    wordlow = word.lower()
                    words_cap.setdefault(wordlow, word)
                    words_vow.setdefault(devowel(wordlow), word)
        
                def solve(query):
                    if query in words_perfect:
                        return query
        
                    queryL = query.lower()
                    if queryL in words_cap:
                        return words_cap[queryL]
        
                    queryLV = devowel(queryL)
                    if queryLV in words_vow:
                        return words_vow[queryLV]
                    return ""
        
                return tuple(map(solve, queries))
        

        4.7.10 - 2025-09-13 18:48:49 +0300 MSK

        Find Most Frequent Vowel and Consonant

        Code

        class Solution:
            def maxFreqSum(self, s: str) -> int:
                freqs = [0] * 26
                for char in s:
                    freqs[ord(char) - 97] += 1
                max_vow, max_con = 0, 0
                for i in range(26):
                    if chr(i + 97) in ("a", "e", "i", "o", "u"):
                        max_vow = max(max_vow, freqs[i])
                    else:
                        max_con = max(max_con, freqs[i])
                return max_vow + max_con
        

        4.7.11 - 2025-09-12 21:22:49 +0300 MSK

        Vowels Game in a String

        Code

        class Solution:
            def doesAliceWin(self, s: str) -> bool:
                return any(c in "aeiou" for c in s)
        

        4.7.12 - 2025-09-11 20:29:02 +0300 MSK

        Sort Vowels in a String

        Code

        class Solution:
            def sortVowels(self, s: str) -> str:
                vowels = []
        
                s_list = list(s)
        
                # collect all vowels
                for i in s_list:
                    if i in "AEIOUaeiou":
                        vowels.append(i)
                
                if vowels == []:
                    return s
        
                # sort the vowels
                vowels.sort()
        
                count = 0
        
                # replace original vowels with sorted ones
                for j in range(len(s)):
                    if s_list[j] in "AEIOUaeiou":
                        s_list[j] = vowels[count]
                        count += 1
        
                return "".join(s_list)
        

        4.7.13 - 2025-09-10 18:11:04 +0300 MSK

        Minimum Number of People to Teach

        Code

        class Solution:
            def minimumTeachings(
                self, n: int, languages: List[List[int]], friendships: List[List[int]]
            ) -> int:
                cncon = set()
                for friendship in friendships:
                    mp = {}
                    conm = False
                    for lan in languages[friendship[0] - 1]:
                        mp[lan] = 1
                    for lan in languages[friendship[1] - 1]:
                        if lan in mp:
                            conm = True
                            break
                    if not conm:
                        cncon.add(friendship[0] - 1)
                        cncon.add(friendship[1] - 1)
        
                max_cnt = 0
                cnt = [0] * (n + 1)
                for friendship in cncon:
                    for lan in languages[friendship]:
                        cnt[lan] += 1
                        max_cnt = max(max_cnt, cnt[lan])
        
                return len(cncon) - max_cnt
        

        4.7.14 - 2025-09-09 18:44:51 +0300 MSK

        Number of People Aware of a Secret

        Code

        class Solution:
            def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
                know, share = deque([(1, 1)]), deque([])
                know_cnt, share_cnt = 1, 0
                for i in range(2, n + 1):
                    if know and know[0][0] == i - delay:
                        know_cnt -= know[0][1]
                        share_cnt += know[0][1]
                        share.append(know[0])
                        know.popleft()
                    if share and share[0][0] == i - forget:
                        share_cnt -= share[0][1]
                        share.popleft()
                    if share:
                        know_cnt += share_cnt
                        know.append((i, share_cnt))
                return (know_cnt + share_cnt) % (10**9 + 7)
        

        4.7.15 - 2025-09-08 18:09:53 +0300 MSK

        Convert Integer to the Sum of Two No-Zero Integers

        Code

        class Solution:
            def getNoZeroIntegers(self, n: int) -> List[int]:
                for A in range(1, n):
                    B = n - A
                    if "0" not in str(A) + str(B):
                        return [A, B]
                return []
        

        4.7.16 - 2025-09-07 11:16:52 +0300 MSK

        Minimum Operations to Equalize Array

        Code

        class Solution:
            def minOperations(self, nums: List[int]) -> int:
                num1 = nums[0]
                for num in nums[1:]:
                    if num != num1:
                        return 1
                return 0
        

        4.7.17 - 2025-09-07 11:00:41 +0300 MSK

        Find N Unique Integers Sum up to Zero

        Code

        class Solution:
            def sumZero(self, n: int) -> List[int]:
                res = []
                for i in range(1, n, 2):
                    res.extend((i, -i))
                if len(res) < n:
                    res.append(0)
                return res
        

        4.7.18 - 2025-09-06 17:38:19 +0300 MSK

        Minimum Operations to Make Array Elements Zero

        Code

        class Solution:
            def get(self, num: int) -> int:
                i = 1
                base = 1
                cnt = 0
                while base <= num:
                    cnt += ((i + 1) // 2) * (min(base * 2 - 1, num) - base + 1)
                    i += 1
                    base *= 2
                return cnt
        
            def minOperations(self, queries: List[List[int]]) -> int:
                res = 0
                for q in queries:
                    res += (self.get(q[1]) - self.get(q[0] - 1) + 1) // 2
                return res
        

        4.7.19 - 2025-09-05 19:23:51 +0300 MSK

        Minimum Operations to Make the Integer Zero

        Code

        class Solution:
            def makeTheIntegerZero(self, num1: int, num2: int) -> int:
                k = 1
                while True:
                    x = num1 - num2 * k
                    if x < k:
                        return -1
                    if k >= x.bit_count():
                        return k
                    k += 1
        

        4.7.20 - 2025-09-04 22:15:30 +0300 MSK

        Find Closest Person

        Code

        class Solution:
            def findClosest(self, x: int, y: int, z: int) -> int:
                dxz = abs(x - z)
                dyz = abs(y - z)
                if dxz < dyz:
                    return 1
                elif dxz > dyz:
                    return 2
                else:
                    return 0
        

        4.7.21 - 2025-09-03 18:20:51 +0300 MSK

        Find the Number of Ways to Place People II

        Code

        class Solution:
            def numberOfPairs(self, points: List[List[int]]) -> int:
                ans = 0
                points.sort(key=lambda x: (x[0], -x[1]))
        
                for i in range(len(points) - 1):
                    pointA = points[i]
                    xMin = pointA[0] - 1
                    xMax = math.inf
                    yMin = -math.inf
                    yMax = pointA[1] + 1
        
                    for j in range(i + 1, len(points)):
                        pointB = points[j]
                        if (
                            pointB[0] > xMin
                            and pointB[0] < xMax
                            and pointB[1] > yMin
                            and pointB[1] < yMax
                        ):
                            ans += 1
                            xMin = pointB[0]
                            yMin = pointB[1]
        
                return ans
        

        4.7.22 - 2025-09-02 20:18:23 +0300 MSK

        Find the Number of Ways to Place People I

        Code

        class Solution:
            def numberOfPairs(self, points: List[List[int]]) -> int:
                ans = 0
                n = len(points)
        
                for i in range(n):
                    pointA = points[i]
                    for j in range(n):
                        pointB = points[j]
                        if i == j or not (
                            pointA[0] <= pointB[0] and pointA[1] >= pointB[1]
                        ):
                            continue
                        if n == 2:
                            ans += 1
                            continue
        
                        illegal = False
                        for k in range(n):
                            if k == i or k == j:
                                continue
        
                            pointTmp = points[k]
                            isXContained = (
                                pointTmp[0] >= pointA[0] and pointTmp[0] <= pointB[0]
                            )
                            isYContained = (
                                pointTmp[1] <= pointA[1] and pointTmp[1] >= pointB[1]
                            )
                            if isXContained and isYContained:
                                illegal = True
                                break
                        if not illegal:
                            ans += 1
                return ans
        

        4.7.23 - 2025-09-01 17:35:05 +0300 MSK

        Maximum Average Pass Ratio

        Code

        class Solution:
            def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
                n = len(classes)
                res = 0
                for i in range(n):
                    pass_, total = classes[i]
                    profit = ((pass_ + 1) / (total + 1)) - (pass_ / total)
                    classes[i] = (-profit, pass_, total)
                heapq.heapify(classes)
                while classes and extraStudents > 0:
                    _, pass_, total = heapq.heappop(classes)
                    if pass_ == total:
                        res += 1
                    else:
                        pass_ += 1
                        total += 1
                        profit = ((pass_ + 1) / (total + 1)) - (pass_ / total)
                        heapq.heappush(classes, (-profit, pass_, total))
                        extraStudents -= 1
                for _, pass_, total in classes:
                    res += pass_ / total
                return res / n
        

        4.7.24 - 2025-08-31 15:07:32 +0300 MSK

        Sudoku Solver

        Code

        class Solution:
            def solveSudoku(self, board: list[list[str]]) -> None:
                n, N = 3, 9
                rows = [[0] * (N + 1) for _ in range(N)]
                cols = [[0] * (N + 1) for _ in range(N)]
                boxes = [[0] * (N + 1) for _ in range(N)]
                sudokuSolved = False
        
                def couldPlace(d, row, col):
                    idx = (row // n) * n + col // n
                    return (rows[row][d] + cols[col][d] + boxes[idx][d]) == 0
        
                def placeNumber(d, row, col):
                    idx = (row // n) * n + col // n
                    rows[row][d] += 1
                    cols[col][d] += 1
                    boxes[idx][d] += 1
                    board[row][col] = str(d)
        
                def removeNumber(d, row, col):
                    idx = (row // n) * n + col // n
                    rows[row][d] -= 1
                    cols[col][d] -= 1
                    boxes[idx][d] -= 1
                    board[row][col] = '.'
        
                def placeNextNumbers(row, col):
                    nonlocal sudokuSolved
                    if row == N - 1 and col == N - 1:
                        sudokuSolved = True
                    elif col == N - 1:
                        backtrack(row + 1, 0)
                    else:
                        backtrack(row, col + 1)
        
                def backtrack(row, col):
                    nonlocal sudokuSolved
                    if board[row][col] == '.':
                        for d in range(1, 10):
                            if couldPlace(d, row, col):
                                placeNumber(d, row, col)
                                placeNextNumbers(row, col)
                                if not sudokuSolved:
                                    removeNumber(d, row, col)
                    else:
                        placeNextNumbers(row, col)
        
                for i in range(N):
                    for j in range(N):
                        if board[i][j] != '.':
                            placeNumber(int(board[i][j]), i, j)
                backtrack(0, 0)
        

        4.7.25 - 2025-08-31 14:18:46 +0300 MSK

        Restore Finishing Order

        Code

        class Solution:
            def recoverOrder(self, order: List[int], friends: List[int]) -> List[int]:
                for i in range(len(order)):
                    if order[i] in friends:
                        order[i] = (i, order[i])
                    else:
                        order[i] = (101, 101)
                order.sort()
                while order[-1] == (101, 101):
                    order.pop()
                for i in range(len(order)):
                    order[i] = order[i][1]
                return order
        

        4.7.26 - 2025-08-31 14:13:40 +0300 MSK

        Find The Least Frequent Digit

        Code

        class Solution:
            def getLeastFrequentDigit(self, n: int) -> int:
                freqs = [0] * 10
                while n > 0:
                    freqs[n % 10] += 1
                    n //= 10
                min_freq, min_num = math.inf, -math.inf
                for i in range(10):
                    if freqs[i] != 0 and (
                        freqs[i] < min_freq or (freqs[i] == min_freq and i < min_num)
                    ):
                        min_freq, min_num = freqs[i], i
                return min_num
        

        4.7.27 - 2025-08-30 20:16:00 +0300 MSK

        Valid Sudoku

        Code

        class Solution:
            def isValidSudoku(self, board: List[List[str]]) -> bool:
                rows = [[False] * 9 for _ in range(9)]
                cols = [[False] * 9 for _ in range(9)]
                boxes = [[False] * 9 for _ in range(9)]
        
                for i in range(9):
                    for j in range(9):
                        if board[i][j] != '.':
                            num = ord(board[i][j]) - ord('1')
                            boxIndex = (i // 3) * 3 + (j // 3)
                            if rows[i][num] or cols[j][num] or boxes[boxIndex][num]:
                                return False
                            rows[i][num] = cols[j][num] = boxes[boxIndex][num] = True
                return True
        

        4.7.28 - 2025-08-29 19:59:52 +0300 MSK

        Alice and Bob Playing Flower Game

        Code

        class Solution:
            def flowerGame(self, n: int, m: int) -> int:
                return (m * n) // 2
        

        4.7.29 - 2025-08-28 16:59:23 +0300 MSK

        Sort Matrix by Diagonals

        Code

        class Solution:
            def sortMatrix(self, grid: List[List[int]]) -> List[List[int]]:
                n = len(grid)
        
                for i in range(n):
                    tmp = [grid[i + j][j] for j in range(n - i)]
                    tmp.sort(reverse=True)
                    for j in range(n - i):
                        grid[i + j][j] = tmp[j]
        
                for j in range(1, n):
                    tmp = [grid[i][j + i] for i in range(n - j)]
                    tmp.sort()
                    for i in range(n - j):
                        grid[i][j + i] = tmp[i]
        
                return grid
        

        4.7.30 - 2025-08-27 16:22:50 +0300 MSK

        Length of Longest V-Shaped Diagonal Segment

        Code

        class Solution:
            def lenOfVDiagonal(self, grid: List[List[int]]) -> int:
                DIRS = [(1, 1), (1, -1), (-1, -1), (-1, 1)]
                m, n = len(grid), len(grid[0])
        
                @cache
                def dfs(cx, cy, direction, turn, target):
                    nx, ny = cx + DIRS[direction][0], cy + DIRS[direction][1]
                    # If it goes beyond the boundary or the next node's value is not the target value, then return
                    if nx < 0 or ny < 0 or nx >= m or ny >= n or grid[nx][ny] != target:
                        return 0
                    turn_int = 1 if turn else 0
                    # Continue walking in the original direction.
                    max_step = dfs(nx, ny, direction, turn, 2 - target)
                    if turn:
                        # Clockwise rotate 90 degrees turn
                        max_step = max(
                            max_step,
                            dfs(nx, ny, (direction + 1) % 4, False, 2 - target),
                        )
                    return max_step + 1
        
                res = 0
                for i in range(m):
                    for j in range(n):
                        if grid[i][j] == 1:
                            for direction in range(4):
                                res = max(res, dfs(i, j, direction, True, 2) + 1)
                return res
        

        4.7.31 - 2025-08-26 09:10:25 +0300 MSK

        String to Integer (atoi)

        Code

        class Solution:
            def myAtoi(self, s: str) -> int:
                digits = []
                sign = None
                found_dig = False
                for char in s:
                    if char.isdigit():
                        digits.append(int(char))
                        found_dig = True
                    elif not found_dig and sign is None and char == " ":
                        continue
                    elif not found_dig and sign is None and char in ("+", "-"):
                        sign = 1
                        if char == "-":
                            sign = -1
                    else:
                        break
                if sign is None:
                    sign = 1
                res = 0
                cnt = 0
                while digits:
                    res += digits.pop() * (10 ** cnt)
                    cnt += 1
                    if res > 2 ** 31 - 1 and sign == 1:
                        return 2 ** 31 - 1
                    elif res > 2 ** 31 and sign == -1:
                        return -(2 ** 31)
                return res * sign 
        

        4.7.32 - 2025-08-26 08:16:39 +0300 MSK

        Reverse Integer

        Code

        class Solution:
            def reverse(self, x: int) -> int:
                digits = []
                neg = 1
                if x < 0:
                    neg = -1
                    x = -x
                while x > 0:
                    digits.append(x % 10)
                    x //= 10
                cnt, res = 0, 0
                while digits:
                    res += digits.pop() * (10 ** cnt)
                    cnt += 1
                    if res > 2 ** 31:
                        return 0
                return res * neg
        

        4.7.33 - 2025-08-26 08:11:15 +0300 MSK

        Maximum Area of Longest Diagonal Rectangle

        Code

        class Solution:
            def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int:
                max_diag, max_area = 0, 0
                for ln, wdth in dimensions:
                    diag, area = ln ** 2 + wdth ** 2, ln * wdth
                    if diag > max_diag or (diag == max_diag and area > max_area):
                        max_diag, max_area = diag, area
                return max_area
        

        4.7.34 - 2025-08-25 17:00:38 +0300 MSK

        My Calendar I

        Code

        class MyCalendar:
            def __init__(self): 
                self.events = SortedList()
        
            def book(self, startTime: int, endTime: int) -> bool:
                insert_index = self.events.bisect_left((startTime, endTime))
                if (
                    insert_index - 1 >= 0 
                    and startTime < self.events[insert_index - 1][1]
                ) or (
                    insert_index < len(self.events) 
                    and self.events[insert_index][0] < endTime
                ):
                    return False
                self.events.add((startTime, endTime))
                return True
        
        
        # Your MyCalendar object will be instantiated and called as such:
        # obj = MyCalendar()
        # param_1 = obj.book(startTime,endTime)
        

        4.7.35 - 2025-08-25 11:40:44 +0300 MSK

        Diagonal Traverse

        Code

        class Solution:
            def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
                res, rows, cols, cur = [], len(mat), len(mat[0]), []
                for i in range(rows + cols):
                    if i < rows:
                        row, col = i, 0
                    else:
                        row, col = rows - 1, (i - rows) + 1 
                    while row >= 0 and col < cols:
                        cur.append(mat[row][col])
                        row, col = row - 1, col + 1
                    if i % 2 != 0:
                        cur.reverse()
                    res.extend(cur)
                    cur.clear()
                return res
                
        
                     
        

        4.7.36 - 2025-08-24 20:51:14 +0300 MSK

        Design Circular Queue

        Code

        class MyCircularQueue:
        
            def __init__(self, k: int):
                self._k = k
                self._q = [-1] * k
                self._i = 0
                self._len = 0
        
            def enQueue(self, value: int) -> bool:
                if self.isFull():
                    return False
                self._q[self._i] = value
                self._i = (self._i + 1) % self._k
                self._len += 1
                return True
        
            def deQueue(self) -> bool:
                if self._len > 0:
                    self._len -= 1
                    return True
                return False
        
            def Front(self) -> int:
                if self.isEmpty():
                    return -1
                return self._q[(self._i - self._len + self._k) % self._k]  
                
            def Rear(self) -> int:
                if self.isEmpty():
                    return -1
                return self._q[(self._i - 1 + self._k) % self._k]
        
            def isEmpty(self) -> bool:
                return self._len == 0
        
            def isFull(self) -> bool:
                return self._len == self._k
        
        
        # Your MyCircularQueue object will be instantiated and called as such:
        # obj = MyCircularQueue(k)
        # param_1 = obj.enQueue(value)
        # param_2 = obj.deQueue()
        # param_3 = obj.Front()
        # param_4 = obj.Rear()
        # param_5 = obj.isEmpty()
        # param_6 = obj.isFull()
        

        4.7.37 - 2025-08-24 19:54:22 +0300 MSK

        Serialize and Deserialize BST

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, x):
        #         self.val = x
        #         self.left = None
        #         self.right = None
        
        class Codec:
        
            def serialize(self, root: Optional[TreeNode]) -> str:
                """Encodes a tree to a single string.
                """
                if root is None:
                    return ""
                left, right = self.serialize(root.left), self.serialize(root.right)
                return f"{root.val}|{len(left)}|{left}{right}"
        
            def deserialize(self, data: str) -> Optional[TreeNode]:
                """Decodes your encoded data to tree.
                """
                if not data:
                    return None
                val, left_len, rest = data.split("|", 2)
                root = TreeNode(int(val))
                root.left = self.deserialize(rest[:int(left_len)])
                root.right = self.deserialize(rest[int(left_len):])
                return root    
        
        # Your Codec object will be instantiated and called as such:
        # Your Codec object will be instantiated and called as such:
        # ser = Codec()
        # deser = Codec()
        # tree = ser.serialize(root)
        # ans = deser.deserialize(tree)
        # return ans
        

        4.7.38 - 2025-08-24 19:38:13 +0300 MSK

        Shuffle an Array

        Code

        class Solution:
        
            def __init__(self, nums: List[int]):
                self._orig = nums
                self._cur = nums.copy()
        
            def reset(self) -> List[int]:
                return self._orig
        
            def shuffle(self) -> List[int]:
                return random.sample(self._orig, k=len(self._orig))
        
        
        # Your Solution object will be instantiated and called as such:
        # obj = Solution(nums)
        # param_1 = obj.reset()
        # param_2 = obj.shuffle()
        

        4.7.39 - 2025-08-24 19:30:45 +0300 MSK

        Maximum Height of a Triangle

        Code

        class Solution:
            def maxHeightOfTriangle(self, red: int, blue: int) -> int:
                return max(self.helper(red, blue), self.helper(blue, red))
            
            def helper(self, red: int, blue: int) -> int:
                h = 0
                i = 1
                
                while True:
                    if i % 2 == 1:
                        if red >= i:
                            red -= i
                        else:
                            break
                    else:
                        if blue >= i:
                            blue -= i
                        else:
                            break
                    h += 1
                    i += 1
                
                return h
        

        4.7.40 - 2025-08-24 19:28:22 +0300 MSK

        Count the Number of Incremovable Subarrays I

        Code

        class Solution:
            def incremovableSubarrayCount(self, nums: List[int]) -> int:
                result = 0
                n = len(nums)
                if n == 0:
                    return 0
                prefix_idx, suffix_idx = 0, n - 1
                while prefix_idx + 1 < n and nums[prefix_idx + 1] > nums[prefix_idx]:
                    prefix_idx += 1
                if prefix_idx == n - 1:
                    return (n * (n + 1)) // 2
                while suffix_idx > 0 and nums[suffix_idx] > nums[suffix_idx - 1]:
                    suffix_idx -= 1
                result += prefix_idx + 1
                result += n - suffix_idx + 1
                i = 0
                j = suffix_idx
                while i <= prefix_idx:
                    while j < n and nums[i] >= nums[j]:
                        j += 1
                    result += n - j
                    i += 1
                return result
        

        4.7.41 - 2025-08-24 19:26:17 +0300 MSK

        GCD of Odd and Even Sums

        Code

        class Solution:
            def gcdOfOddEvenSums(self, n: int) -> int:
                odd_num = 1 + (n - 1) * 2
                even_num = 2 + (n - 1) * 2
                odd_sum = (n * (1 + odd_num)) // 2
                even_sum = (n * (2 + even_num)) // 2
                return math.gcd(odd_sum, even_sum)
        

        4.7.42 - 2025-08-24 19:18:26 +0300 MSK

        Flip Square Submatrix Vertically

        Code

        class Solution:
            def reverseSubmatrix(self, grid: List[List[int]], x: int, y: int, k: int) -> List[List[int]]:
                rows, cols = len(grid), len(grid[0])
                for col in range(y, y + k):
                    for row_dlt in range(k // 2):
                        row1 = x + row_dlt
                        row2 = (x + k - 1) - row_dlt
                        grid[row1][col], grid[row2][col] = grid[row2][col], grid[row1][col]
                return grid
        

        4.7.43 - 2025-08-24 19:07:06 +0300 MSK

        Find Books with Polarized Opinions

        Code

         SELECT r.book_id,
               b.title,
               b.author,
               b.genre,
               b.pages,
               Max(r.session_rating) - Min(r.session_rating) rating_spread,
               Round(( Sum(CASE WHEN r.session_rating < 3 THEN 1 ELSE 0 END + CASE WHEN
                                   r.session_rating >
                                   3 THEN 1 ELSE 0 END) ) / COUNT(r.session_id) ::
                     Decimal(10, 2), 2)                      polarization_score
        FROM   reading_sessions r
               INNER JOIN books b USING(book_id)
        GROUP  BY r.book_id,
                  b.title,
                  b.author,
                  b.genre,
                  b.pages
        HAVING COUNT(r.session_id) > 4
               AND Max(r.session_rating) > 3
               AND Min(r.session_rating) < 3
               AND Round(( Sum(CASE WHEN r.session_rating < 3 THEN 1 ELSE 0 END + CASE
                               WHEN
                                           r.session_rating >
                                           3 THEN 1 ELSE 0 END) ) / COUNT(r.session_id)
                         ::
                         Decimal(
                             10, 2), 2) >= 0.6
        ORDER  BY polarization_score desc,
                  b.title desc  
        

        4.7.44 - 2025-08-24 19:02:12 +0300 MSK

        Trionic Array I

        Code

        class Solution:
            def isTrionic(self, nums: List[int]) -> bool:
                seg, n = 0, len(nums)
                for i in range(1, n):
                    cur, prv = nums[i], nums[i - 1]
                    if cur == prv:
                        return False
                    if seg == 0:
                        if cur < prv:
                            if i == 1:
                                return False
                            seg = 1
                    elif seg == 1:
                        if cur > prv:
                            seg = 2
                    elif seg == 2:
                        if cur < prv:
                            return False
                return seg == 2 
        

        4.7.45 - 2025-08-24 18:57:13 +0300 MSK

        Earliest Finish Time for Land and Water Rides I

        Code

        from typing import List
        
        class Solution:
            def earliestFinishTime(self,landStartTime: List[int],landDuration: List[int],waterStartTime: List[int],waterDuration: List[int]) -> int:
                res = float('inf')
                n, m = len(landStartTime), len(waterStartTime)
                for i in range(n):
                    a, d = landStartTime[i], landDuration[i]
                    for j in range(m):
                        b, e = waterStartTime[j], waterDuration[j]
                        land_end = a + d
                        start_water = max(land_end, b)
                        finish1 = start_water + e
                        water_end = b + e
                        start_land = max(water_end, a)
                        finish2 = start_land + d
                        res = min(res, finish1, finish2)
                return res
        

        4.7.46 - 2025-08-24 18:52:47 +0300 MSK

        Check Divisibility by Digit Sum and Product

        Code

        class Solution:
            def checkDivisibility(self, n: int) -> bool:
                sm, pr, num = 0, 1, n
                while num > 0:
                    dig = num % 10
                    num //= 10
                    sm += dig
                    pr *= dig
                return n % (sm + pr) == 0
        

        4.7.47 - 2025-08-24 18:50:32 +0300 MSK

        Coupon Code Validator

        Code

        class Solution:
            def validateCoupons(self, code: List[str], businessLine: List[str], isActive: List[bool]) -> List[str]:
                res, n = [], len(code)
                b_order = {"electronics": 0, "grocery": 1, "pharmacy": 2, "restaurant": 3}
                for i in range(n):
                    if (
                        isActive[i] 
                        and code[i] 
                        and re.match("^[a-zA-Z0-9_]+$", code[i]) 
                        and businessLine[i] in (
                            "electronics", "grocery", "pharmacy", "restaurant"
                        )
                    ):
                        res.append(i)
                def sort(i: int) -> tuple[str, str]:
                    return (b_order[businessLine[i]], code[i])
                res.sort(key=sort)
                for i in range(len(res)):
                    res[i] = code[res[i]]
                return res
        

        4.7.48 - 2025-08-24 18:39:15 +0300 MSK

        Hexadecimal and Hexatrigesimal Conversion

        Code

        class Solution:
            def concatHex36(self, n: int) -> str:
                res = []
                for num, base in ((n ** 3, 36), (n ** 2, 16)):
                    while num > 0:
                        dig = num % base
                        if dig < 10:
                            res.append(str(dig))
                        else:
                            res.append(chr((dig - 10) + 65))
                        num //= base
                res.reverse()
                return "".join(res)
        

        4.7.49 - 2025-08-24 18:38:15 +0300 MSK

        Hexadecimal and Hexatrigesimal Conversion

        Code

        class Solution:
            def concatHex36(self, n: int) -> str:
                res, cur = [], []
                for num, base in ((n ** 2, 16), (n ** 3, 36)):
                    while num > 0:
                        dig = num % base
                        if dig < 10:
                            cur.append(str(dig))
                        else:
                            cur.append(chr((dig - 10) + 65))
                        num //= base
                    cur.reverse()
                    res.extend(cur)
                    cur.clear()
                return "".join(res)
        

        4.7.50 - 2025-08-24 18:22:04 +0300 MSK

        Check if Any Element Has Prime Frequency

        Code

        class Solution:
            def checkPrimeFrequency(self, nums: List[int]) -> bool:
                def is_prime(v: int) -> bool:
                    for i in range(2, int(math.sqrt(v)) + 1):
                        if v % i == 0:
                            return False
                    return True
                freqs = [0] * 101
                for num in nums:
                    freqs[num] += 1
                for freq in freqs:
                    if freq > 1 and is_prime(freq):
                        return True
                return False
        

        4.7.51 - 2025-08-24 18:15:48 +0300 MSK

        Generate Tag for Video Caption

        Code

        class Solution:
            def generateTag(self, caption: str) -> str:
                res, n, cur = [], len(caption), []
                for i in range(n):
                    ch = caption[i]
                    if ch.isalpha():
                        cur.append(ch.lower())
                    if (ch == " " or i + 1 == n) and cur:
                        if res:
                            cur[0] = cur[0].upper()
                        res.append("".join(cur))
                        cur.clear()
                return "".join(itertools.chain("#", res))[:100]
                
        

        4.7.52 - 2025-08-24 18:07:04 +0300 MSK

        Find Books with No Available Copies

        Code

        SELECT 
            book_id, 
            MAX(title) AS title, 
            MAX(author) AS author, 
            MAX(genre) AS genre, 
            MAX(publication_year) AS publication_year, 
            MAX(total_copies) AS current_borrowers 
        FROM
            (
                SELECT 
                    book_id,
                    title,
                    author, 
                    genre,publication_year, 
                    total_copies,
                    total_copies AS total_remain 
                FROM 
                    library_books
                UNION 
                    ALL
                SELECT 
                    book_id, 
                    '', 
                    '', 
                    '', 
                    1000, 
                    0, 
                    -1 
                FROM 
                    borrowing_records 
                WHERE 
                    return_date IS NULL
            ) sub
        GROUP BY 
            book_id
        HAVING 
            SUM(total_remain) = 0
        ORDER BY 
            current_borrowers DESC, 
            title;
        

        4.7.53 - 2025-08-24 18:01:04 +0300 MSK

        Find Minimum Log Transportation Cost

        Code

        class Solution:
            def minCuttingCost(self, n: int, m: int, k: int) -> int:
                ans = 0
                if m <= k and n <= k:
                    return 0
                if m > k and n <= k:
                    ans += (m - k) * k
                if n > k and m <= k:
                    ans += (n - k) * k
                return ans
        

        4.7.54 - 2025-08-24 17:55:59 +0300 MSK

        Smallest Index With Digit Sum Equal to Index

        Code

        class Solution:
            def smallestIndex(self, nums: List[int]) -> int:
                for i in range(len(nums)):
                    num = nums[i]
                    sm = 0
                    while num > 0:
                        sm += num % 10
                        num //= 10
                    if sm == i:
                        return i
                return -1
        

        4.7.55 - 2025-08-24 17:54:29 +0300 MSK

        Minimum Deletions for At Most K Distinct Characters

        Code

        class Solution:
            def minDeletion(self, s: str, k: int) -> int:
                freqs, n = [0] * 26, len(s)
                for i in range(n):
                    freqs[ord(s[i]) - 97] += 1
                freqs.sort()
                res = 0
                for i in range(26 - k):
                    res += freqs[i]
                return res
        

        4.7.56 - 2025-08-24 17:52:40 +0300 MSK

        Minimum Deletions for At Most K Distinct Characters

        Code

        class Solution:
            def minDeletion(self, s: str, k: int) -> int:
                freqs, n = [0] * 26, len(s)
                for i in range(n):
                    freqs[ord(s[i]) - 97] += 1
                freqs.sort(reverse=True)
                res = 0
                while len(freqs) > k:
                    res += freqs.pop()
                return res
        

        4.7.57 - 2025-08-24 17:46:18 +0300 MSK

        Find Most Frequent Vowel and Consonant

        Code

        class Solution:
            def maxFreqSum(self, s: str) -> int:
                freqs, n = [0] * 26, len(s)
                for i in range(n):
                    freqs[ord(s[i]) - 97] += 1
                max_vow, max_con = 0, 0
                vow = tuple(ord(ch) - 97 for ch in ("a", "e", "i", "o", "u"))
                for i in range(26):
                    if i in vow:
                        max_vow = max(max_vow, freqs[i])
                    else:
                        max_con = max(max_con, freqs[i])
                return max_vow + max_con
        

        4.7.58 - 2025-08-24 17:42:32 +0300 MSK

        Maximum Product of Two Digits

        Code

        class Solution:
            def maxProduct(self, n: int) -> int:
                num1, num2 = -math.inf, -math.inf
                while n > 0:
                    dig = n % 10
                    if dig > num2:
                        num1, num2 = num2, dig
                    elif dig > num1:
                        num1 = dig
                    n //= 10
                return num1 * num2
        

        4.7.59 - 2025-08-24 17:41:29 +0300 MSK

        Maximum Product of Two Digits

        Code

        class Solution:
            def maxProduct(self, n: int) -> int:
                dig = []
                while n > 0:
                    heapq.heappush(dig, -(n % 10))
                    n //= 10
                return abs(heapq.heappop(dig) * heapq.heappop(dig))
        

        4.7.60 - 2025-08-24 17:40:23 +0300 MSK

        Find Closest Person

        Code

        class Solution:
            def findClosest(self, x: int, y: int, z: int) -> int:
                diff1, diff2 = abs(z - x), abs(z - y)
                if diff1 == diff2:
                    return 0
                if diff1 < diff2:
                    return 1
                return 2
        

        4.7.61 - 2025-08-24 17:38:35 +0300 MSK

        Minimum Operations to Make Array Sum Divisible by K

        Code

        class Solution:
            def minOperations(self, nums: List[int], k: int) -> int:
                return sum(nums) % k
        

        4.7.62 - 2025-08-24 17:36:34 +0300 MSK

        Minimum Pair Removal to Sort Array I

        Code

        class Solution:
            def minimumPairRemoval(self, nums: List[int], ans = 0) -> int:
                def notSorted(nums: List[int]) -> bool:
                    for a, b in pairwise(nums):
                        if a > b: 
                            return True
                    return False
                
                while notSorted(nums):
                    minSum, mnIdx = inf, -1
                    for i, pair in enumerate(pairwise(nums)):
                        if sum(pair) < minSum:
                            minSum, mnIdx, delIdx = sum(pair), i, i + 1
                    nums[mnIdx] = minSum
                    del nums[delIdx]
                    ans += 1
                return ans 
        

        4.7.63 - 2025-08-24 17:22:24 +0300 MSK

        Minimum Cost to Reach Every Position

        Code

        class Solution:
            def minCosts(self, cost: List[int]) -> List[int]:
                
                return list(accumulate(cost, min))
        

        4.7.64 - 2025-08-24 17:12:42 +0300 MSK

        Reverse Degree of a String

        Code

        class Solution:
            def reverseDegree(self, s: str) -> int:
                res, n = 0, len(s)
                for i in range(n):
                    res += (i + 1) * (26 - (ord(s[i]) - 97))
                return res
        

        4.7.65 - 2025-08-24 17:10:49 +0300 MSK

        Maximum Containers on a Ship

        Code

        class Solution:
            def maxContainers(self, n: int, w: int, maxWeight: int) -> int:
                return min(maxWeight // w, n * n)
        

        4.7.66 - 2025-08-24 17:08:09 +0300 MSK

        Unique 3-Digit Even Numbers

        Code

        class Solution:
            def totalNumbers(self, digits: List[int]) -> int:
                enc = set()
                p = [a * 100 + b * 10 + c for a, b, c in itertools.permutations(digits, 3)]
                for num in p:
                    if num not in enc and len(str(num)) == 3:
                        if num % 2 == 0:
                            enc.add(num)
                return len(enc)
        

        4.7.67 - 2025-08-24 17:02:11 +0300 MSK

        Find the Largest Almost Missing Integer

        Code

        class Solution:
            def largestInteger(self, nums: List[int], k: int) -> int:
                n = len(nums)
                subarray_count = defaultdict(int)
                for i in range(n - k + 1):
                    for num in set(nums[i:i+k]):
                        subarray_count[num] += 1
                res = -1
                for num, count in subarray_count.items():
                    if count == 1:
                        res = max(res, num)
                return res
        

        4.7.68 - 2025-08-24 16:02:46 +0300 MSK

        Transform Array by Parity

        Code

        class Solution:
            def transformArray(self, nums: List[int]) -> List[int]:
                for i in range(len(nums)):
                    val = nums[i]
                    if val % 2 == 0:
                        nums[i] = 0
                    else:
                        nums[i] = 1
                nums.sort()
                return nums
        

        4.7.69 - 2025-08-24 16:00:53 +0300 MSK

        Find Products with Valid Serial Numbers

        Code

        SELECT 
            *
        FROM 
            Products
        WHERE 
            description ~ '\mSN[0-9]{4}-[0-9]{4}\M'
        ORDER BY 
            product_id ASC;
        

        4.7.70 - 2025-08-24 15:55:14 +0300 MSK

        Check If Digits Are Equal in String After Operations I

        Code

        class Solution:
            def hasSameDigits(self, s: str) -> bool:
                stack = list(map(int, s))
                stack.reverse()
                while len(stack) > 2:
                    prev = stack.pop()
                    for i in reversed(range(len(stack))):
                        stack[i], prev = (prev + stack[i]) % 10, stack[i]
                return stack[0] == stack[1]
        

        4.7.71 - 2025-08-24 15:40:47 +0300 MSK

        Find Special Substring of Length K

        Code

        class Solution:
            def hasSpecialSubstring(self, s: str, k: int) -> bool:
                cnt, n = 0, len(s)
                for i in range(n):
                    if i > 0 and s[i] == s[i - 1]:
                        cnt += 1
                    else:
                        cnt = 1
                    if cnt != k:
                        continue
                    if (
                        i - cnt >= 0 and s[i - cnt] == s[i]
                    ) or (
                        i + 1 < n and s[i + 1] == s[i]
                    ):
                        cnt = 1
                    else:
                        return True
                return False
        

        4.7.72 - 2025-08-24 15:35:22 +0300 MSK

        Sum of Good Numbers

        Code

        class Solution:
            def sumOfGoodNumbers(self, nums: List[int], k: int) -> int:
                res, n = 0, len(nums)
                for i in range(n):
                    left, right, cur = -1, -1, nums[i]
                    if i - k >= 0:
                        left = nums[i - k]
                    if i + k < n:
                        right = nums[i + k]
                    if left < cur > right:
                        res += cur
                return res
        

        4.7.73 - 2025-08-24 15:32:58 +0300 MSK

        Maximum Difference Between Even and Odd Frequency I

        Code

        class Solution:
            def maxDifference(self, s: str) -> int:
                freqs, n = [0] * 26, len(s)
                for i in range(n):
                    freqs[ord(s[i]) - 97] += 1
                max_odd, min_even = -math.inf, math.inf
                for i in range(26):
                    freq = freqs[i]
                    if freq == 0:
                        continue
                    if freq % 2 == 0:
                        min_even =  min(min_even, freq)
                    else:
                        max_odd = max(max_odd, freq)
                return max_odd - min_even
        

        4.7.74 - 2025-08-24 15:21:21 +0300 MSK

        Find Valid Pair of Adjacent Digits in String

        Code

        class Solution:
            def findValidPair(self, s: str) -> str:
                freqs, n = [0] * 10, len(s)
                for i in range(n):
                    freqs[int(s[i])] += 1
                for i in range(1, n):
                    cur, prv = int(s[i]), int(s[i - 1])
                    if cur != prv and freqs[cur] == cur and freqs[prv] == prv:
                        return f"{prv}{cur}"
                return ""
        

        4.7.75 - 2025-08-24 15:17:24 +0300 MSK

        Find Valid Emails

        Code

        SELECT 
            user_id,
            email
        FROM 
            users
        WHERE 
            email ~ '^\w+@[A-Za-z]+\.com$'
        ORDER BY 
            user_id ASC;
        

        4.7.76 - 2025-08-24 15:14:50 +0300 MSK

        Count Partitions with Even Sum Difference

        Code

        class Solution:
            def countPartitions(self, nums: List[int]) -> int:
                sm, n = [0] * len(nums), len(nums)
                sm[0] = nums[0]
                for i in range(n):
                    sm[i] = sm[i - 1] + nums[i]
                res = 0
                for i in range(n - 1):
                    left = sm[i]
                    right = sm[-1] - left
                    res += abs(right - left) % 2 == 0
                return res
        

        4.7.77 - 2025-08-24 15:11:09 +0300 MSK

        Sum of Variable Length Subarrays

        Code

        class Solution:
            def subarraySum(self, nums: List[int]) -> int:
                sm, n = [0] * len(nums), len(nums)
                sm[0] = nums[0]
                for i in range(1, n):
                    sm[i] = sm[i - 1] + nums[i]
                res = 0
                for i in range(n):
                    left = max(0, i - nums[i])
                    left_sum = 0
                    if left > 0:
                        left_sum = sm[left - 1]
                    res += sm[i] - left_sum
                return res
        

        4.7.78 - 2025-08-24 15:07:53 +0300 MSK

        Maximum Difference Between Adjacent Elements in a Circular Array

        Code

        class Solution:
            def maxAdjacentDistance(self, nums: List[int]) -> int:
                res = abs(nums[0] - nums[-1])
                for i in range(1, len(nums)):
                    res = max(res, abs(nums[i] - nums[i - 1]))
                return res
        

        4.7.79 - 2025-08-24 15:06:30 +0300 MSK

        Zigzag Grid Traversal With Skip

        Code

        class Solution:
            def zigzagTraversal(self, grid: List[List[int]]) -> List[int]:
                m, n = len(grid), len(grid[0])
                res = []
                skip = False
                for row in range(m):
                    if row % 2 == 0:
                        start, end, step = 0, n, 1
                    else:
                        start, end, step = n - 1, -1, -1
                    for col in range(start, end, step):
                        if not skip:
                            res.append(grid[row][col])
                        skip = not skip
                return res
        

        4.7.80 - 2025-08-24 15:00:31 +0300 MSK

        Maximum Subarray With Equal Products

        Code

        class Solution:
            def maxLength(self, A: List[int]) -> int:
                N = len(A)
                ans = 2
                last = {}
                i = 0
                for j, x in enumerate(A):
                    for p in prime_divisors(x):
                        i = max(i, last.get(p, -1) + 1)
                        last[p] = j
                    ans = max(ans, j - i + 1)
                
                return ans
        
        def prime_divisors(x):
            d = 2
            while d * d <= x:
                if x % d == 0:
                    x //= d
                    while x % d == 0:
                        x //= d
                    yield d
                d += 1 + d & 1
            
            if x > 1:
                yield x
        

        4.7.81 - 2025-08-24 14:57:30 +0300 MSK

        Substring Matching Pattern

        Code

        class Solution:
            def hasMatch(self, string: str, pattern: str) -> bool:
                left_part, right_part = pattern.split("*")
                left_idx = string.find(left_part)
                right_idx = string.find(right_part, left_idx + len(left_part))
                return left_idx != -1 and right_idx != -1
        

        4.7.82 - 2025-08-24 14:47:52 +0300 MSK

        Minimum Operations to Make Columns Strictly Increasing

        Code

        class Solution:
            def minimumOperations(self, grid: List[List[int]]) -> int:
                m, n = len(grid), len(grid[0])
                res = 0
                for col in range(n):
                    prv = grid[0][col]
                    for row in range(1, m):
                        val = grid[row][col]
                        if val > prv:
                            prv = val
                        else:
                            diff = (prv + 1) - val
                            res += diff
                            prv += 1
                return res
        

        4.7.83 - 2025-08-24 14:42:38 +0300 MSK

        Minimum Number of Operations to Make Elements in Array Distinct

        Code

        class Solution:
            def minimumOperations(self, nums: List[int]) -> int:
                freqs, n = [0] * 101, len(nums)
                for i in range(n):
                    freqs[nums[i]] += 1
                res = 0
                for i in range(0, n, 3):
                    if max(freqs) == 1:
                        return res
                    res += 1
                    for j in range(i, min(i + 3, n)):
                        freqs[nums[j]] -= 1
                return res
        

        4.7.84 - 2025-08-24 14:38:49 +0300 MSK

        Count Subarrays of Length Three With a Condition

        Code

        class Solution:
            def countSubarrays(self, nums: List[int]) -> int:
                res, n = 0, len(nums)
                for i in range(n - 2):
                    if nums[i] + nums[i + 2] == nums[i + 1] / 2:
                        res += 1
                return res
        

        4.7.85 - 2025-08-24 14:36:54 +0300 MSK

        Button with Longest Push Time

        Code

        class Solution:
            def buttonWithLongestTime(self, events: List[List[int]]) -> int:
                (mx_idx, mx_time), n = events[0], len(events)
                for i in range(n):
                    (cur_idx, cur_time), (prv_idx, prv_time) = events[i], events[i - 1]
                    diff = cur_time - prv_time
                    if diff > mx_time or (diff == mx_time and cur_idx < mx_idx):
                        mx_idx, mx_time = cur_idx, diff
                return mx_idx
        

        4.7.86 - 2025-08-24 14:33:39 +0300 MSK

        Transformed Array

        Code

        class Solution:
            def constructTransformedArray(self, nums: List[int]) -> List[int]:
                n = len(nums)
                res = [0] * n
                for i in range(n):
                    num = nums[i]
                    if num == 0:
                        val = 0
                    elif num > 0:
                        val = nums[(i + num) % n]
                    else:
                        val = nums[(i - -num + n) % n]
                    res[i] = val
                return res
        

        4.7.87 - 2025-08-24 14:28:25 +0300 MSK

        Smallest Number With All Set Bits

        Code

        class Solution:
            def smallestNumber(self, n: int) -> int:
                res = 0
                while n > 0:
                    res = (res << 1) | 1
                    n //= 2
                return res
        

        4.7.88 - 2025-08-24 14:25:47 +0300 MSK

        Minimum Positive Sum Subarray

        Code

        class Solution:
            def minimumSumSubarray(self, nums: List[int], l: int, r: int) -> int:
                sm, n = [0] * len(nums), len(nums)
                cur = 0
                for i in range(n):
                    cur += nums[i]
                    sm[i] = cur
                res = math.inf
                for i in range(n):
                    left = 0
                    if i > 0:
                        left = sm[i - 1]
                    for j in range(i + l - 1, min(i + r, n)):
                        cur = sm[j] - left
                        if cur > 0:
                            res = min(res, cur)
                if res == math.inf:
                    return -1
                return res
        

        4.7.89 - 2025-08-24 14:09:37 +0300 MSK

        Stone Removal Game

        Code

        class Solution:
            def canAliceWin(self, n: int) -> bool:
                cnt = 10
                while True:
                    if n >= cnt:
                        n -= cnt
                        cnt -= 1
                    else:
                        return False
                    if n >= cnt:
                        n -= cnt
                        cnt -= 1
                    else:
                        return True
        

        4.7.90 - 2025-08-24 14:03:51 +0300 MSK

        Make Array Elements Equal to Zero

        Code

        class Solution:
            def countValidSelections(self, nums: List[int]) -> int:
                n, res = len(nums), 0
                left, right = [0 for _ in range(n)], [0 for _ in range(n)]
                for i in range(1, n):
                    left[i] = left[i - 1] + nums[i - 1]
                    right[-i - 1] = right[-i] + nums[-i]
                for i, num in enumerate(nums):
                    if num != 0: continue
                    if left[i] == right[i]: res += 2
                    if abs(left[i] - right[i]) == 1: res += 1
                return res
        

        4.7.91 - 2025-08-24 13:57:16 +0300 MSK

        Adjacent Increasing Subarrays Detection I

        Code

        class Solution:
            def hasIncreasingSubarrays(self, nums: List[int], k: int) -> bool:
                n = len(nums)
                cnt = 1
                prv_cnt = 0
                for i in range(1, n):
                    cur, prv = nums[i], nums[i - 1]
                    if cur > prv:
                        cnt += 1
                    else:
                        prv_cnt, cnt = cnt, 1
                    if cnt >= 2 * k or prv_cnt >= k and cnt >= k:
                        return True
                return False
        

        4.7.92 - 2025-08-24 13:46:58 +0300 MSK

        Smallest Divisible Digit Product I

        Code

        class Solution:
            def smallestNumber(self, n: int, t: int) -> int:
                while True:
                    cur = n
                    prd = 1
                    while cur > 0:
                        prd *= cur % 10
                        if prd == 0:
                            break
                        cur //= 10
                    if prd % t == 0:
                        return n
                    n += 1
        

        4.7.93 - 2025-08-24 13:33:19 +0300 MSK

        Check Balanced String

        Code

        class Solution:
            def isBalanced(self, num: str) -> bool:
                sm, n = 0, len(num)
                for i in range(n):
                    if i % 2 == 0:
                        sm += int(num[i])
                    else:
                        sm -= int(num[i])
                return sm == 0
        

        4.7.94 - 2025-08-24 13:31:22 +0300 MSK

        Find the Original Typed String I

        Code

        class Solution:
            def possibleStringCount(self, word: str) -> int:
                res, n = 1, len(word)
                for i in range(1, n):
                    cur, prev = word[i], word[i - 1]
                    if cur == prev:
                        res += 1
                return res
        

        4.7.95 - 2025-08-24 13:27:05 +0300 MSK

        Find X-Sum of All K-Long Subarrays I

        Code

        class Solution:
            def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:
        
                def do_sum (idx: int)-> int:
        
                    ctr = Counter(nums[idx:idx + k])
                    most_freq = nlargest(x, ctr, key = lambda y: (ctr[y], y))
        
                    return sum(map(lambda y: y * ctr[y], most_freq))
        
        
                return tuple(map(do_sum,range(len(nums)+1 - k)))
        

        4.7.96 - 2025-08-24 13:21:47 +0300 MSK

        Construct the Minimum Bitwise Array I

        Code

        class Solution:
            def minBitwiseArray(self, nums: List[int]) -> List[int]:
                ans = []
                for i in nums:
                    for j in range(i):
                        if j | (j + 1) == i:
                            ans.append(j)
                            break
                    else:
                        ans.append(-1)
                return ans
        

        4.7.97 - 2025-08-24 13:10:51 +0300 MSK

        Find the K-th Character in String Game I

        Code

        class Solution:
            def kthCharacter(self, k: int) -> str:
                res = 0
                while k != 1:
                    ln = k.bit_length() - 1
                    if (1 << ln) == k:
                        ln -= 1
                    k -= 1 << ln
                    res += 1
                return chr(res + 97)
        

        4.7.98 - 2025-08-24 13:05:10 +0300 MSK

        Minimum Element After Replacement With Digit Sum

        Code

        class Solution:
            def minElement(self, nums: List[int]) -> int:
                res = math.inf
                for num in nums:
                    cur = 0
                    while num > 0:
                        cur += num % 10
                        num //= 10
                    res = min(res, cur)
                return res
        

        4.7.99 - 2025-08-24 12:59:57 +0300 MSK

        The Two Sneaky Numbers of Digitville

        Code

        class Solution:
            def getSneakyNumbers(self, nums: List[int]) -> List[int]:
                n = len(nums) - 2
                xor_all = 0
                for num in nums:
                    xor_all ^= num
                for num in range(n):
                    xor_all ^= num
                rightmost_bit = xor_all & -xor_all
                dup1, dup2 = 0, 0
                for num in nums:
                    if num & rightmost_bit:
                        dup1 ^= num
                    else:
                        dup2 ^= num
                for num in range(n):
                    if num & rightmost_bit:
                        dup1 ^= num
                    else:
                        dup2 ^= num
                return [dup1, dup2]
        

        4.7.100 - 2025-08-24 12:47:23 +0300 MSK

        Find Indices of Stable Mountains

        Code

        class Solution:
            def stableMountains(self, height: List[int], threshold: int) -> List[int]:
                res, n = [], len(height)
                for i in range(1, n):
                    cur, prv = height[i], height[i - 1]
                    if prv > threshold:
                        res.append(i)
                return res
        

        4.7.101 - 2025-08-24 12:44:46 +0300 MSK

        Convert Date to Binary

        Code

        class Solution:
            def convertDateToBinary(self, date: str) -> str:
                res, cur = [], []
                for num in map(int, (date[:4], date[5:7], date[-2:])):
                    while num > 0:
                        cur.append(num & 1)
                        num >>= 1
                    cur.reverse()
                    res.append("".join(map(str, cur)))
                    cur.clear()
                return "-".join(res)
        

        4.7.102 - 2025-08-24 12:44:03 +0300 MSK

        Convert Date to Binary

        Code

        class Solution:
            def convertDateToBinary(self, date: str) -> str:
                res, cur = [], []
                for num in map(int, (date[:4], date[5:7], date[-2:])):
                    while num > 0:
                        cur.append(num % 2)
                        num //= 2
                    cur.reverse()
                    res.append("".join(map(str, cur)))
                    cur.clear()
                return "-".join(res)
        

        4.7.103 - 2025-08-24 12:38:10 +0300 MSK

        Check if Two Chessboard Squares Have the Same Color

        Code

        class Solution:
            def checkTwoChessboards(self, coordinate1: str, coordinate2: str) -> bool:
                row1, col1 = ord(coordinate1[0]) - 97, int(coordinate1[1]) - 1
                row2, col2 = ord(coordinate2[0]) - 97, int(coordinate2[1]) - 1
                if row1 % 2 == 0:
                    is_black1 = col1 % 2 == 0
                else:
                    is_black1 = col1 % 2 != 0
                if row2 % 2 == 0:
                    is_black2 = col2 % 2 == 0
                else:
                    is_black2 = col2 % 2 != 0
                return is_black1 == is_black2
        

        4.7.104 - 2025-08-24 12:34:32 +0300 MSK

        Find the Key of the Numbers

        Code

        class Solution:
            def generateKey(self, num1: int, num2: int, num3: int) -> int:
                res = 0
                cnt = 0
                while num1 > 0 and num2 > 0 and num3 > 0:
                    res += min(num1 % 10, num2 % 10, num3 % 10) * (10 ** cnt)
                    cnt += 1
                    num1 //= 10
                    num2 //= 10
                    num3 //= 10
                return res
        

        4.7.105 - 2025-08-24 12:31:27 +0300 MSK

        Final Array State After K Multiplication Operations I

        Code

        class Solution:
            def getFinalState(self, nums: List[int], k: int, multiplier: int):
                hp = [(val, i) for i, val in enumerate(nums)]
                heapq.heapify(hp)
                for _ in range(k):
                    _, i = heapq.heappop(hp)
                    nums[i] *= multiplier
                    heapq.heappush(hp, (nums[i], i))
                return nums
        

        4.7.106 - 2025-08-24 12:29:48 +0300 MSK

        Final Array State After K Multiplication Operations I

        Code

        class Solution:
            def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:
                pos, n = defaultdict(list), len(nums)
                hp = nums.copy()
                heapq.heapify(hp)
                for i in reversed(range(n)):
                    heapq.heappush(pos[nums[i]], i)
                while k > 0:
                    k -= 1
                    val = heapq.heappop(hp)
                    new_val = val * multiplier
                    heapq.heappush(hp, new_val)
                    idx = heapq.heappop(pos[val])
                    nums[idx] = new_val
                    heapq.heappush(pos[new_val], idx)
                return nums
        
                
        

        4.7.107 - 2025-08-24 12:20:45 +0300 MSK

        Count Substrings That Satisfy K-Constraint I

        Code

        class Solution:
            def countKConstraintSubstrings(self, s: str, k: int) -> int:
                res, n, ones, l = 0, len(s), 0, 0
                for r in range(n):
                    ones += int(s[r])
                    while (ones > k) and ((r - l + 1) - ones) > k:
                        ones -= int(s[l])
                        l += 1
                    res += r - l + 1
                return res
        

        4.7.108 - 2025-08-24 11:46:23 +0300 MSK

        Snake in Matrix

        Code

        class Solution:
            def finalPositionOfSnake(self, n: int, commands: List[str]) -> int:
                col, row = 0, 0
                for cmd in commands:
                    if cmd == "RIGHT":
                        col += 1
                    elif cmd == "UP":
                        row -= 1
                    elif cmd == "DOWN":
                        row += 1
                    else:
                        col -= 1
                return row * n + col
        

        4.7.109 - 2025-08-24 11:43:54 +0300 MSK

        Find the Number of Winning Players

        Code

        class Solution:
            def winningPlayerCount(self, n: int, pick: List[List[int]]) -> int:
                res, n, freqs = 0, len(pick), [[0] * 11 for _ in range(11)]
                for i in range(n):
                    pl, cl = pick[i]
                    freqs[pl][cl] += 1
                for i in range(len(freqs)):
                    if max(freqs[i]) > i:
                        res += 1
                return res
        

        4.7.110 - 2025-08-24 10:55:08 +0300 MSK

        Longest Subarray of 1’s After Deleting One Element

        Code

        class Solution:
            def longestSubarray(self, nums: List[int]) -> int:
                res, n, cnt1, cnt2 = 0, len(nums), 0, 0
                for i in range(len(nums)):
                    cur = nums[i]
                    if cur == 1:
                        cnt2 += 1
                        res = max(res, cnt1 + cnt2)
                    elif cur == 0:
                        cnt1, cnt2 = cnt2, 0
                if res == n:
                    return res - 1
                return res
        

        4.7.111 - 2025-08-23 20:17:19 +0300 MSK

        Find if Digit Game Can Be Won

        Code

        class Solution:
            def canAliceWin(self, nums: List[int]) -> bool:
                sm_single, sm_double, sm_all = 0, 0, 0
                for num in nums:
                    if num < 10:
                        sm_single += num
                    elif num < 100:
                        sm_double += num
                    sm_all += num
                return sm_single > (sm_all - sm_single) or sm_double > (sm_all - sm_double) 
        

        4.7.112 - 2025-08-23 19:28:34 +0300 MSK

        Number of Bit Changes to Make Two Integers Equal

        Code

        class Solution:
            def minChanges(self, n: int, k: int) -> int:
                res = 0
                if n < k:
                    return -1
                while k > 0 or n > 0:
                    n1, k1 = n & 1, k & 1
                    if n1 != k1 and n1 == 0 and k1 == 1:
                        return -1
                    if n1 != k1:
                        res += 1
                    n >>= 1
                    k >>= 1
                return res
        

        4.7.113 - 2025-08-23 18:30:08 +0300 MSK

        Find the Minimum Area to Cover All Ones II

        Code

        class Solution:
            def minimumSum2(
                self, grid: List[List[int]], u: int, d: int, l: int, r: int
            ) -> int:
                min_i = len(grid)
                max_i = 0
                min_j = len(grid[0])
                max_j = 0
        
                for i in range(u, d + 1):
                    for j in range(l, r + 1):
                        if grid[i][j] == 1:
                            min_i = min(min_i, i)
                            min_j = min(min_j, j)
                            max_i = max(max_i, i)
                            max_j = max(max_j, j)
        
                return (
                    (max_i - min_i + 1) * (max_j - min_j + 1)
                    if min_i <= max_i
                    else sys.maxsize // 3
                )
        
            def rotate(self, vec: List[List[int]]) -> List[List[int]]:
                n = len(vec)
                m = len(vec[0]) if n > 0 else 0
                ret = [[0] * n for _ in range(m)]
        
                for i in range(n):
                    for j in range(m):
                        ret[m - j - 1][i] = vec[i][j]
        
                return ret
        
            def solve(self, grid: List[List[int]]) -> int:
                n = len(grid)
                m = len(grid[0]) if n > 0 else 0
                res = n * m
        
                for i in range(n - 1):
                    for j in range(m - 1):
                        res = min(
                            res,
                            self.minimumSum2(grid, 0, i, 0, m - 1)
                            + self.minimumSum2(grid, i + 1, n - 1, 0, j)
                            + self.minimumSum2(grid, i + 1, n - 1, j + 1, m - 1),
                        )
        
                        res = min(
                            res,
                            self.minimumSum2(grid, 0, i, 0, j)
                            + self.minimumSum2(grid, 0, i, j + 1, m - 1)
                            + self.minimumSum2(grid, i + 1, n - 1, 0, m - 1),
                        )
        
                for i in range(n - 2):
                    for j in range(i + 1, n - 1):
                        res = min(
                            res,
                            self.minimumSum2(grid, 0, i, 0, m - 1)
                            + self.minimumSum2(grid, i + 1, j, 0, m - 1)
                            + self.minimumSum2(grid, j + 1, n - 1, 0, m - 1),
                        )
        
                return res
        
            def minimumSum(self, grid: List[List[int]]) -> int:
                rgrid = self.rotate(grid)
                return min(self.solve(grid), self.solve(rgrid))
        

        4.7.114 - 2025-08-22 21:36:17 +0300 MSK

        Find the Winning Player in Coin Game

        Code

        class Solution:
            def winningPlayer(self, x: int, y: int) -> str:
                y //= 4
                x = min(x, y)
                if x % 2 == 1:
                    return "Alice"
                else:
                    return "Bob"
        

        4.7.115 - 2025-08-22 21:29:25 +0300 MSK

        Lexicographically Smallest String After a Swap

        Code

        class Solution:
            def getSmallestString(self, s: str) -> str:
                res = list(s)
                for i in range(len(s) - 1):
                    cur, nxt = int(s[i]), int(s[i + 1])
                    if cur % 2 == nxt % 2 and cur > nxt:
                        res[i], res[i + 1] = s[i + 1], s[i]
                        break        
                return "".join(res)
        

        4.7.116 - 2025-08-22 21:16:52 +0300 MSK

        Find the Encrypted String

        Code

        class Solution:
            def getEncryptedString(self, s: str, k: int) -> str:
                res = []
                for i in range(len(s)):
                    res.append(s[(i + k) % len(s)])
                return "".join(res)
        

        4.7.117 - 2025-08-22 21:13:56 +0300 MSK

        Alternating Groups I

        Code

        class Solution:
            def numberOfAlternatingGroups(self, colors: List[int]) -> int:
                res = 0
                if colors[0] != colors[-1] and colors[0] != colors[1]:
                    res += 1
                if colors[-1] != colors[-2] and colors[-1] != colors[0]:
                    res += 1
                for i in range(1, len(colors) - 1):
                    if colors[i] != colors[i - 1] and colors[i] != colors[i + 1]:
                        res += 1
                return res
        

        4.7.118 - 2025-08-22 21:08:45 +0300 MSK

        Minimum Average of Smallest and Largest Elements

        Code

        class Solution:
            def minimumAverage(self, nums: List[int]) -> float:
                av = []
                nums.sort()
                for i in range(len(nums) // 2):
                    heapq.heappush(av, nums[i] + nums[len(nums) - i - 1])
                return heapq.heappop(av) / 2
        

        4.7.119 - 2025-08-22 21:06:36 +0300 MSK

        Find Minimum Operations to Make All Elements Divisible by Three

        Code

        class Solution:
            def minimumOperations(self, nums: List[int]) -> int:
                res = 0
                for i in range(len(nums)):
                    res += nums[i] % 3 != 0
                return res
        

        4.7.120 - 2025-08-22 21:05:07 +0300 MSK

        Find Minimum Operations to Make All Elements Divisible by Three

        Code

        class Solution:
            def minimumOperations(self, nums: List[int]) -> int:
                res = 0
                for i in range(len(nums)):
                    res += min(nums[i] % 3, ((nums[i] // 3) + 1) * 3 - nums[i])
                return res
        

        4.7.121 - 2025-08-22 21:02:15 +0300 MSK

        Count Pairs That Form a Complete Day I

        Code

        class Solution:
            def countCompleteDayPairs(self, hours: List[int]) -> int:
                freqs = [0] * 24
                for i in range(len(hours)):
                    freqs[hours[i] % 24] += 1
                res = 0
                for i in range(len(hours)):
                    hr = hours[i] % 24
                    freqs[hr] -= 1
                    if hr == 0:
                        res += freqs[hr]
                    else:
                        res += freqs[24 - hr]
                return res
        

        4.7.122 - 2025-08-22 20:53:33 +0300 MSK

        Find the Child Who Has the Ball After K Seconds

        Code

        class Solution:
            def numberOfChild(self, n: int, k: int) -> int:
                circleback = (n - 1) * 2
                k %= circleback
                if k < n:
                    return k
                return circleback - k
        

        4.7.123 - 2025-08-22 20:44:21 +0300 MSK

        Clear Digits

        Code

        class Solution:
            def clearDigits(self, s: str) -> str:
                res = []
                for i in range(len(s)):
                    ch = s[i]
                    if not ch.isdigit():
                        res.append(ch)
                    elif res:
                        res.pop()
                return "".join(res)
        

        4.7.124 - 2025-08-22 20:41:37 +0300 MSK

        Minimum Number of Chairs in a Waiting Room

        Code

        class Solution:
            def minimumChairs(self, s: str) -> int:
                left = 0
                res = 0
                for i in range(len(s)):
                    if s[i] == "E":
                        if left > 0:
                            left -= 1
                        else:
                            res += 1
                    else:
                        left += 1
                return res
        

        4.7.125 - 2025-08-22 20:34:34 +0300 MSK

        Find the Number of Good Pairs I

        Code

        class Solution:
            def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
                freqs = [0] * 51
                for i in range(len(nums2)):
                    freqs[nums2[i]] += 1
                res = 0
                for i in range(len(nums1)):
                    for num2 in range(1, len(freqs)):
                        if nums1[i] % (num2 * k) == 0:
                            res += freqs[num2]
                return res
        

        4.7.126 - 2025-08-22 20:29:48 +0300 MSK

        Find the XOR of Numbers Which Appear Twice

        Code

        class Solution:
            def duplicateNumbersXOR(self, nums: List[int]) -> int:
                freqs = [0] * 51
                res = 0
                for i in range(len(nums)):
                    freqs[nums[i]] += 1
                    if freqs[nums[i]] == 2:
                        res ^= nums[i]
                return res
        

        4.7.127 - 2025-08-22 20:27:37 +0300 MSK

        Special Array I

        Code

        class Solution:
            def isArraySpecial(self, nums: List[int]) -> bool:
                for i in range(1, len(nums)):
                    cur, prev = nums[i] % 2 == 0, nums[i - 1] % 2 == 0
                    if cur == prev:
                        return False
                return True
        

        4.7.128 - 2025-08-22 20:25:28 +0300 MSK

        Permutation Difference between Two Strings

        Code

        class Solution:
            def findPermutationDifference(self, s: str, t: str) -> int:
                pos = [0] * 26
                for i in range(len(s)):
                    pos[ord(s[i]) - 97] += i
                res = 0
                for i in range(len(t)):
                    res += abs(i - pos[ord(t[i]) - 97])
                return res
                
        

        4.7.129 - 2025-08-22 20:22:48 +0300 MSK

        Check if Grid Satisfies Conditions

        Code

        class Solution:
            def satisfiesConditions(self, grid: List[List[int]]) -> bool:
                rows, cols = len(grid), len(grid[0])
                for row in range(rows):
                    for col in range(cols):
                        val = grid[row][col]
                        if row + 1 < rows and val != grid[row + 1][col]:
                            return False
                        if col + 1 < cols and val == grid[row][col + 1]:
                            return False
                return True 
        

        4.7.130 - 2025-08-22 20:20:58 +0300 MSK

        Valid Word

        Code

        class Solution:
            def isValid(self, word: str) -> bool:
                vws = ('a', 'e', 'i', 'o', 'u')
                if len(word) < 3:
                    return False
                has_vw, has_cons = False, False
                for i in range(len(word)):
                    ch = word[i]
                    if ch.isalpha():
                        if ch.lower() in vws:
                            has_vw = True
                        else:
                            has_cons = True
                    elif not ch.isdigit():
                        return False
                return has_vw and has_cons
        

        4.7.131 - 2025-08-22 20:15:56 +0300 MSK

        Find the Integer Added to Array I

        Code

        class Solution:
            def addedInteger(self, nums1: List[int], nums2: List[int]) -> int:
                nums1.sort()
                nums2.sort()
                return nums2[0] - nums1[0]
        

        4.7.132 - 2025-08-22 20:12:59 +0300 MSK

        Make a Square with the Same Color

        Code

        class Solution:
            def canMakeSquare(self, grid: List[List[str]]) -> bool:
                rows, cols = len(grid), len(grid[0])
                moves = ((0, 0), (0, -1), (-1, -1), (-1, 0))
                for row in range(1, rows):
                    for col in range(1, cols):
                        cnt = 0
                        for row_dlt, col_dlt in moves:
                            if grid[row + row_dlt][col + col_dlt] == "W":
                                cnt += 1
                            else:
                                cnt -= 1
                        if cnt in (2, -2, 4, -4):
                            return True
                return False
        

        4.7.133 - 2025-08-22 20:03:50 +0300 MSK

        Count the Number of Special Characters I

        Code

        class Solution:
            def numberOfSpecialChars(self, word: str) -> int:
                freqs = [0] * 26
                res = 0
                for i in range(len(word)):
                    char = word[i]
                    idx = ord(char)
                    if char.isupper():
                        idx -= 65
                        freqs[idx] |= 0x01
                    else:
                        idx -= 97
                        freqs[idx] |= 0x10
                for i in range(len(freqs)):
                    freq = freqs[i]
                    if freq ^ 0x11 == 0:
                        res += 1
                return res
        

        4.7.134 - 2025-08-22 19:58:17 +0300 MSK

        Latest Time You Can Obtain After Replacing Characters

        Code

        class Solution:
            def findLatestTime(self, time_str):
                len_time_str = len(time_str)
                ret_val = ''
                i = 0
                while (i < len_time_str):
                    c = time_str[i]
                    if (c == '?'):
                        if (i == 0):
                            if (time_str[i+1] == '?'):
                                ret_val += '1'
                            elif (time_str[i+1] in ('0', '1')):
                                ret_val += '1'
                            else:
                                ret_val += '0'
                        elif (i == 1):
                            if (time_str[i-1] == '?'):
                                ret_val += '1'
                            elif (time_str[i-1] in ('0')):
                                ret_val += '9'
                            elif (time_str[i-1] in ('1')):
                                ret_val += '1'
                            else:
                                ret_val += '0'
                        elif (i == 3):
                            ret_val += '5'
                        elif (i == 4):
                            ret_val += '9'
                    else:
                        ret_val += c
                    i += 1
                return ret_val
        

        4.7.135 - 2025-08-22 19:49:07 +0300 MSK

        Longest Strictly Increasing or Strictly Decreasing Subarray

        Code

        class Solution:
            def longestMonotonicSubarray(self, nums: List[int]) -> int:
                inc_len, dec_len, cur_len, cur_state = 1, 1, 1, 0
                for i in range(1, len(nums)):
                    cur, prev = nums[i], nums[i - 1]
                    if cur > prev:
                        if cur_state == 1:
                            cur_len += 1
                        else:
                            cur_state = 1
                            cur_len = 2
                        inc_len = max(inc_len, cur_len)
                    elif cur == prev:
                        cur_len = 1
                        cur_state = 0
                    else:
                        if cur_state == -1:
                            cur_len += 1
                        else:
                            cur_state = -1
                            cur_len = 2
                        dec_len = max(dec_len, cur_len)
                return max(inc_len, dec_len)
                    
        

        4.7.136 - 2025-08-22 19:43:35 +0300 MSK

        Harshad Number

        Code

        class Solution:
            def sumOfTheDigitsOfHarshadNumber(self, x: int) -> int:
                cur = x
                sm = 0
                while cur > 0:
                    sm += cur % 10
                    cur //= 10
                if x % sm == 0:
                    return sm
                return -1
        

        4.7.137 - 2025-08-22 19:42:24 +0300 MSK

        Shortest Subarray With OR at Least K I

        Code

        class Solution:
            def minimumSubarrayLength(self, nums: List[int], k: int) -> int:
                n = len(nums)
                min_len = math.inf
                for i in range(n):
                    curr = 0
                    for j in range(i, n):
                        curr |= nums[j]
                        if curr >= k:
                            min_len = min(min_len , j - i + 1)
                            break
                if min_len == math.inf:
                    return -1
                return min_len
        

        4.7.138 - 2025-08-22 19:24:16 +0300 MSK

        Maximum Length Substring With Two Occurrences

        Code

        class Solution:
            def maximumLengthSubstring(self, s: str) -> int:
                ans = ii = 0 
                freq = Counter()
                for i, ch in enumerate(s): 
                    freq[ch] += 1
                    while freq[ch] == 3: 
                        freq[s[ii]] -= 1
                        ii += 1
                    ans = max(ans, i - ii + 1)
                return ans
        

        4.7.139 - 2025-08-22 19:19:46 +0300 MSK

        Existence of a Substring in a String and Its Reverse

        Code

        class Solution:
            def isSubstringPresent(self, s: str) -> bool:
                for i in range(1, len(s)):
                    cur, prev = s[i], s[i - 1]
                    for j in range(i, len(s)):
                        cur2, prev2 = s[j], s[j - 1]
                        if cur == prev2 and prev == cur2:
                            return True
                return False
        

        4.7.140 - 2025-08-22 19:14:44 +0300 MSK

        Find the Sum of Encrypted Integers

        Code

        class Solution:
            def sumOfEncryptedInt(self, nums: List[int]) -> int:
                res = 0
                for i in range(len(nums)):
                    cur = nums[i]
                    max_dig = 0
                    enc = 0
                    cnt = 0
                    while cur > 0:
                        max_dig = max(max_dig, cur % 10)
                        cur //= 10
                        enc += 10 ** cnt
                        cnt += 1
                    enc *= max_dig
                    res += enc
                return res
        

        4.7.141 - 2025-08-22 19:10:19 +0300 MSK

        Apple Redistribution into Boxes

        Code

        class Solution:
            def minimumBoxes(self, apple: List[int], capacity: List[int]) -> int:
                apples = sum(apple)
                capacity.sort(reverse=True)
                for i in range(len(capacity)):
                    apples = max(apples - capacity[i], 0)
                    if apples == 0:
                        return i + 1
                raise Exception
        

        4.7.142 - 2025-08-22 19:03:00 +0300 MSK

        Distribute Elements Into Two Arrays I

        Code

        class Solution:
            def resultArray(self, nums):
                len_nums = len(nums)
                arr1 = [nums[0]]
                arr2 = [nums[1]]
                for i in range(2, len(nums)):
                    if arr1[-1] > arr2[-1]:
                        arr1.append(nums[i])
                    else:
                        arr2.append(nums[i])
                arr1.extend(arr2)
                return arr1
        

        4.7.143 - 2025-08-22 18:58:03 +0300 MSK

        Minimum Operations to Exceed Threshold Value I

        Code

        class Solution:
            def minOperations(self, nums: List[int], k: int) -> int:
                nums.sort()
                for i in range(len(nums)):
                    if nums[i] >= k:
                        return i
                return len(nums)
        

        4.7.144 - 2025-08-22 18:56:27 +0300 MSK

        Split the Array

        Code

        class Solution:
            def isPossibleToSplit(self, nums: List[int]) -> bool:
                freqs = [0] * 101
                for num in nums:
                    freqs[num] += 1
                    if freqs[num] == 3:
                        return False
                return True
        

        4.7.145 - 2025-08-22 18:53:34 +0300 MSK

        Count Prefix and Suffix Pairs I

        Code

        class Solution:
            def countPrefixSuffixPairs(self, words: List[str]) -> int:
                res = 0
                for i in range(len(words)):
                    w1 = words[i]
                    for j in range(i + 1, len(words)):
                        w2 = words[j]
                        if w2.startswith(w1) and w2.endswith(w1):
                            res += 1
                return res
        

        4.7.146 - 2025-08-22 18:48:54 +0300 MSK

        Maximum Number of Operations With the Same Score I

        Code

        class Solution:
            def maxOperations(self, nums: List[int]) -> int:
                target = sum(nums[:2])
                res = 1
                for i in range(2, len(nums) - 1, 2):
                    if sum(nums[i:i + 2]) == target:
                        res += 1
                    else:
                        break
                return res
        

        4.7.147 - 2025-08-22 18:46:45 +0300 MSK

        Modify the Matrix

        Code

        class Solution:
            def modifiedMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
                rows, cols = len(matrix), len(matrix[0])
                for col in range(cols):
                    max_val = -1
                    for row in range(rows):
                        max_val = max(max_val, matrix[row][col])
                    for row in range(rows):
                        if matrix[row][col] == -1:
                            matrix[row][col] = max_val
                return matrix
        

        4.7.148 - 2025-08-22 18:44:22 +0300 MSK

        Ant on the Boundary

        Code

        class Solution:
            def returnToBoundaryCount(self, nums: List[int]) -> int:
                res = 0
                pos = nums[0]
                for num in nums[1:]:
                    pos += num
                    if pos == 0:
                        res += 1
                return res
        

        4.7.149 - 2025-08-22 18:43:10 +0300 MSK

        Type of Triangle

        Code

        class Solution:
            def triangleType(self, nums: List[int]) -> str:
                s1, s2, s3 = nums
                if s1 == s2 == s3:
                    return "equilateral"
                if s1 + s2 <= s3 or s1 + s3 <= s2 or s2 + s3 <= s1:
                    return "none"
                if s1 == s2 or s2 == s3 or s1 == s3:
                    return "isosceles"
                if s1 != s2 and s2 != s3 and s1 != s3:
                    return "scalene"
                return "none"
        

        4.7.150 - 2025-08-22 18:39:40 +0300 MSK

        Number of Changing Keys

        Code

        class Solution:
            def countKeyChanges(self, s: str) -> int:
                res = 0
                for i in range(1, len(s)):
                    cur, prev = ord(s[i]), ord(s[i - 1])
                    if cur < 97:
                        cur += 32
                    if prev < 97:
                        prev += 32
                    if cur != prev:
                        res += 1
                return res
        

        4.7.151 - 2025-08-22 18:38:14 +0300 MSK

        Number of Changing Keys

        Code

        class Solution:
            def countKeyChanges(self, s: str) -> int:
                res = 0
                for i in range(1, len(s)):
                    cur, prev = s[i].lower(), s[i - 1].lower()
                    if cur != prev:
                        res += 1
                return res
        

        4.7.152 - 2025-08-22 18:36:52 +0300 MSK

        Minimum Number of Pushes to Type Word I

        Code

        class Solution:
            def minimumPushes(self, word: str) -> int:
                freqs = [0] * 26
                for char in word:
                    freqs[ord(char) - 97] += 1
                freqs.sort()
                res = 0
                for i in range(26):
                    freq = freqs[26 - i - 1]
                    if freq == 0:
                        break
                    res += freq * (i // 8 + 1)
                return res
        

        4.7.153 - 2025-08-22 18:30:44 +0300 MSK

        Minimum Number of Pushes to Type Word I

        Code

        class Solution:
            def minimumPushes(self, word: str) -> int:
                freqs = [0] * 26
                for char in word:
                    freqs[ord(char) - 97] += 1
                freqs.sort()
                cost = 1
                res = 0
                while freqs and freqs[-1] != 0:
                    for _ in range(8):
                        if not freqs:
                            break
                        freq = freqs.pop()
                        if freq == 0:
                            break
                        res += freq * cost
                    cost += 1
                return res
        

        4.7.154 - 2025-08-22 18:25:20 +0300 MSK

        Divide an Array Into Subarrays With Minimum Cost I

        Code

        class Solution:
            def minimumCost(self, nums: List[int]) -> int:
                nums.reverse()
                first = nums.pop()
                nums.sort()
                return first + sum(nums[:2])
        

        4.7.155 - 2025-08-22 18:22:55 +0300 MSK

        Maximum Area of Longest Diagonal Rectangle

        Code

        class Solution:
            def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int:
                max_diag, max_area = 0, 0
                for length, width in dimensions:
                    diag = length ** 2 + width ** 2
                    area = length * width
                    if diag > max_diag or (diag == max_diag and area > max_area):
                        max_diag, max_area = diag, area
                return max_area
        

        4.7.156 - 2025-08-22 18:19:44 +0300 MSK

        Smallest Missing Integer Greater Than Sequential Prefix Sum

        Code

        class Solution:
            def missingInteger(self, nums: List[int]) -> int:
                s = set(nums)
                x = nums[0] - 1
                seqSum = 0
                for i in nums:
                    if i - x == 1:
                        seqSum += i
                        x = i
                    else:
                        break
                index = seqSum
                while True:
                    if index not in s:
                        return index
                    index += 1
        

        4.7.157 - 2025-08-22 17:02:28 +0300 MSK

        Check if Bitwise OR Has Trailing Zeros

        Code

        class Solution:
            def hasTrailingZeros(self, nums: List[int]) -> bool:
                cnt = 0
                for num in nums:
                    if num & 1 == 0:
                        cnt += 1
                        if cnt == 2:
                            return True
                return False
        

        4.7.158 - 2025-08-22 16:56:33 +0300 MSK

        Minimum Number Game

        Code

        class Solution:
            def numberGame(self, nums: List[int]) -> List[int]:
                res = []
                nums.sort(reverse=True)
                while nums:
                    al, bob = nums.pop(), nums.pop()
                    res.extend((bob, al))
                return res
        

        4.7.159 - 2025-08-22 14:49:18 +0300 MSK

        Find Missing and Repeated Values

        Code

        class Solution:
            def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
                n = len(grid)
                freqs = [0] * (n ** 2 + 1)
                res1 = None
                for row in grid:
                    for num in row:
                        freqs[num] += 1
                        if freqs[num] == 2:
                            res1 = num
                return res1, freqs[1:].index(0) + 1
        

        4.7.160 - 2025-08-22 14:41:39 +0300 MSK

        Count Tested Devices After Test Operations

        Code

        class Solution:
            def countTestedDevices(self, batteryPercentages: List[int]) -> int:
                res = 0
                for i, perc in enumerate(batteryPercentages):
                    if perc - res > 0:
                        res += 1
                return res
        

        4.7.161 - 2025-08-22 14:33:33 +0300 MSK

        Find Common Elements Between Two Arrays

        Code

        class Solution:
            def findIntersectionValues(self, nums1: List[int], nums2: List[int]) -> List[int]:
                freqs1, freqs2 = [0] * 101, [0] * 101
                for num in nums1:
                    freqs1[num] += 1
                for num in nums2:
                    freqs2[num] += 1
                res1, res2 = 0, 0
                for num, freq in enumerate(freqs1):
                    if freqs2[num] > 0:
                        res1 += freq
                for num, freq in enumerate(freqs2):
                    if freqs1[num] > 0:
                        res2 += freq
                return res1, res2
        

        4.7.162 - 2025-08-22 14:30:04 +0300 MSK

        Find the Peaks

        Code

        class Solution:
            def findPeaks(self, mountain: List[int]) -> List[int]:
                res = []
                for i in range(1, len(mountain) - 1):
                    if mountain[i - 1] < mountain[i] > mountain[i + 1]:
                        res.append(i)
                return res
        

        4.7.163 - 2025-08-22 14:28:05 +0300 MSK

        Matrix Similarity After Cyclic Shifts

        Code

        class Solution:
            def areSimilar(self, mat: List[List[int]], k: int) -> bool:
                cols = len(mat[0])
                for row in range(len(mat)):
                    is_even = row % 2 == 0
                    for col in range(cols):
                        if is_even:
                            new_col = (col - k + cols) % cols
                        else:
                            new_col = (col + k) % cols
                        if mat[row][col] != mat[row][new_col]:
                            return False
                return True
        

        4.7.164 - 2025-08-22 14:23:13 +0300 MSK

        Find Words Containing Character

        Code

        class Solution:
            def findWordsContaining(self, words: List[str], x: str) -> List[int]:
                for i in range(len(words)):
                    if x in words[i]:
                        words[i] = i
                    else:
                        words[i] = -1
                words.sort(reverse=True)
                while words and words[-1] == -1:
                    words.pop()
                return words
        

        4.7.165 - 2025-08-22 14:20:44 +0300 MSK

        Find Words Containing Character

        Code

        class Solution:
            def findWordsContaining(self, words: List[str], x: str) -> List[int]:
                res = []
                for i, word in enumerate(words):
                    if x in word:
                        res.append(i)
                return res 
        

        4.7.166 - 2025-08-22 14:19:56 +0300 MSK

        Make Three Strings Equal

        Code

        class Solution:
            def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int:
                n1, n2, n3 = len(s1), len(s2), len(s3)
                for i in range(max(n1, n2, n3)):
                    fail = True
                    if i < n1 and i < n2 and i < n3:
                        c1, c2, c3 = s1[i], s2[i], s3[i]
                        if c1 == c2 and c2 == c3:
                            fail = False
                    if not fail:
                        continue
                    if i == 0:
                        return -1
                    return max(n1 - i, 0) + max(n2 - i, 0) + max(n3 - i, 0)
                return 0
        

        4.7.167 - 2025-08-22 14:06:34 +0300 MSK

        Maximum Strong Pair XOR I

        Code

        class Solution:
            def maximumStrongPairXor(self, nums: List[int]) -> int:
                nums.sort()
                n, l, r, res = len(nums), 0, 0, 0
                while r < n:
                    num1, num2 = nums[l], nums[r]
                    if num2 - num1 > num1:
                        l += 1
                        continue
                    for i in range(l, r):
                        res = max(res, nums[i] ^ num2)
                    r += 1
                return res
        

        4.7.168 - 2025-08-22 13:59:13 +0300 MSK

        Maximum Strong Pair XOR I

        Code

        class Solution:
            def maximumStrongPairXor(self, nums: List[int]) -> int:
                max_xor = 0
                for i in range(len(nums)):
                    for j in range(i + 1, len(nums)):
                        num1, num2 = nums[i], nums[j]
                        if abs(num2 - num1) <= min(num1, num2):
                            max_xor = max(max_xor, num1 ^ num2)
                return max_xor 
        

        4.7.169 - 2025-08-22 13:58:21 +0300 MSK

        Maximum Strong Pair XOR I

        Code

        class Solution:
            def maximumStrongPairXor(self, nums: List[int]) -> int:
                max_xor = 0
                for num1, num2 in itertools.permutations(nums, 2):
                    if abs(num2 - num1) <= min(num1, num2):
                        max_xor = max(max_xor, num1 ^ num2)
                return max_xor 
        

        4.7.170 - 2025-08-22 13:53:08 +0300 MSK

        Distribute Candies Among Children I

        Code

        class Solution:
            def distributeCandies(self, n: int, limit: int) -> int:
                min_first = max(0, n - 2 * limit)
                max_first = min(n, limit)
                ways = 0
                for i in range(min_first, max_first + 1):
                    N = n - i
                    min_ch2 = max(0, N - limit)
                    max_ch2 = min(N, limit)
                    ways += max_ch2 - min_ch2 + 1
                return ways
        

        4.7.171 - 2025-08-22 13:44:20 +0300 MSK

        Find Champion I

        Code

        class Solution:
            def findChampion(self, grid: List[List[int]]) -> int:
                loses = [False] * len(grid)
                for row in range(len(grid)):
                    for col in range(len(grid)):
                        if row == col:
                            continue
                        val = grid[row][col]
                        if val == 1:
                            loses[col] = True
                        else:
                            loses[row] = True
                return loses.index(False)
        

        4.7.172 - 2025-08-22 13:37:11 +0300 MSK

        Find the K-or of an Array

        Code

        class Solution:
            def findKOr(self, nums: List[int], k: int) -> int:
                freqs = [0] * 31
                for num in nums:
                    i = 0    
                    while num > 0:
                        if num & 1 == 1:
                            freqs[i] += 1
                        i += 1
                        num >>= 1
                res = 0
                for i, freq in enumerate(freqs):
                    if freq >= k:
                        res |= 1 << i
                return res
        

        4.7.173 - 2025-08-22 09:54:03 +0300 MSK

        Find the Minimum Area to Cover All Ones I

        Code

        class Solution:
            def minimumArea(self, grid: List[List[int]]) -> int:
                min_row, max_row = math.inf, -math.inf
                min_col, max_col = math.inf, -math.inf
                for row in range(len(grid)):
                    for col in range(len(grid[0])):
                        if grid[row][col] == 0:
                            continue
                        min_row, max_row = min(min_row, row), max(max_row, row)
                        min_col, max_col = min(min_col, col), max(max_col, col)
                return (max_row - min_row + 1) * (max_col - min_col + 1)
        

        4.7.174 - 2025-08-21 19:04:22 +0300 MSK

        Subarrays Distinct Element Sum of Squares I

        Code

        class Solution:
            def sumCounts(self, nums: List[int]) -> int:
                n = len(nums)
                result = 0
                for i in range(n):
                    s = set()
                    for j in range(i, n):
                        s.add(nums[j])
                        result += len(s) ** 2
                return result
        

        4.7.175 - 2025-08-21 19:01:40 +0300 MSK

        Method Chaining

        Code

        import pandas as pd
        
        def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
            return animals[animals['weight'] > 100].sort_values(by='weight', ascending=False)[['name']]
        

        4.7.176 - 2025-08-21 18:59:14 +0300 MSK

        Reshape Data: Melt

        Code

        import pandas as pd
        
        def meltTable(report: pd.DataFrame) -> pd.DataFrame:
            report = report.melt(
                id_vars=["product"],
                value_vars=["quarter_1", "quarter_2", "quarter_3", "quarter_4"],
                var_name="quarter",
                value_name="sales",
            )
            return report
        

        4.7.177 - 2025-08-21 18:58:06 +0300 MSK

        Reshape Data: Pivot

        Code

        import pandas as pd
        
        def pivotTable(weather: pd.DataFrame) -> pd.DataFrame:
            ans = weather.pivot(index='month', columns='city', values='temperature')
            return ans
        

        4.7.178 - 2025-08-21 18:57:41 +0300 MSK

        Minimum Sum of Mountain Triplets I

        Code

        class Solution:
            def minimumSum(self, nums: List[int]) -> int:
                n = len(nums)
                min_left, min_right = [0] * n, [0] * n
                cur_min = math.inf
                for i in range(n):
                    cur_min = min(cur_min, nums[i])
                    min_left[i] = cur_min
                cur_min = math.inf
                for i in reversed(range(n)):
                    cur_min = min(cur_min, nums[i])
                    min_right[i] = cur_min
                min_sum = math.inf
                for i in range(1, n - 1):
                    left, mid, right = min_left[i - 1], nums[i], min_right[i + 1]
                    if left < mid > right:
                        min_sum = min(min_sum, left + mid + right)
                if min_sum == math.inf:
                    return -1
                return min_sum
        

        4.7.179 - 2025-08-21 18:50:35 +0300 MSK

        Reshape Data: Concatenate

        Code

        import pandas as pd
        
        def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame:
            return pd.concat([df1, df2], axis=0)
        

        4.7.180 - 2025-08-21 18:50:21 +0300 MSK

        Find Indices With Index and Value Difference I

        Code

        class Solution:
            def findIndices(self, A: List[int], d: int, valueDifference: int) -> List[int]:
                mini = maxi = 0
                for i in range(d, len(A)):
                    if A[i - d] < A[mini]: 
                        mini = i - d
                    if A[i - d] > A[maxi]: 
                        maxi = i - d
                    if A[i] - A[mini] >= valueDifference: 
                        return [mini, i]
                    if A[maxi] - A[i] >= valueDifference: 
                        return [maxi, i]
                return [-1, -1]
        

        4.7.181 - 2025-08-21 18:45:02 +0300 MSK

        Fill Missing Data

        Code

        import pandas as pd
        
        def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame:
            products['quantity'].fillna(0, inplace=True)
            return products
        

        4.7.182 - 2025-08-21 18:35:19 +0300 MSK

        Change Data Type

        Code

        import pandas as pd
        
        def changeDatatype(students: pd.DataFrame) -> pd.DataFrame:
            students = students.astype({'grade': int})
            return students
        

        4.7.183 - 2025-08-21 18:35:00 +0300 MSK

        Longest Unequal Adjacent Groups Subsequence I

        Code

        class Solution:
            def getLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]:
                res = [words[0]]
                prev = groups[0]
                for i in range(1, len(groups)):
                    cur = groups[i]
                    if cur == prev:
                        continue
                    prev = cur
                    res.append(words[i])
                return res
        

        4.7.184 - 2025-08-21 18:34:31 +0300 MSK

        Rename Columns

        Code

        import pandas as pd
        
        def renameColumns(students: pd.DataFrame) -> pd.DataFrame:
            students = students.rename(
                columns={
                    "id": "student_id",
                    "first": "first_name",
                    "last": "last_name",
                    "age": "age_in_years",
                }
            )
            return students
        

        4.7.185 - 2025-08-21 18:30:25 +0300 MSK

        Modify Columns

        Code

        import pandas as pd
        
        def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame:
            employees['salary'] = employees['salary'] * 2
            return employees
        

        4.7.186 - 2025-08-21 18:30:11 +0300 MSK

        Last Visited Integers

        Code

        class Solution:
            def lastVisitedIntegers(self, nums: List[int]) -> List[int]:
                enc = []
                res = []
                m1_cnt = 0
                for num in nums:
                    if num != -1:
                        m1_cnt = 0
                        enc.append(num)
                        continue
                    m1_cnt += 1
                    if m1_cnt <= len(enc):
                        res.append(enc[len(enc) - (m1_cnt - 1) - 1])
                    else:
                        res.append(-1)
                return res
        

        4.7.187 - 2025-08-21 18:24:42 +0300 MSK

        Drop Missing Data

        Code

        import pandas as pd
        
        def dropMissingData(students: pd.DataFrame) -> pd.DataFrame:
            students.dropna(subset=['name'], inplace=True)
            return students
        

        4.7.188 - 2025-08-21 18:24:23 +0300 MSK

        Divisible and Non-divisible Sums Difference

        Code

        class Solution:
            def differenceOfSums(self, n: int, m: int) -> int:
                al = n * (1 + n) // 2
                div = (n // m) * (m + (n - (n % m))) // 2
                non_div = al - div
                return (al - div) - div
        

        4.7.189 - 2025-08-21 18:18:09 +0300 MSK

        Drop Duplicate Rows

        Code

        import pandas as pd
        
        def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame:
            customers.drop_duplicates(subset='email', keep='first', inplace=True)
            return customers
        

        4.7.190 - 2025-08-21 18:17:44 +0300 MSK

        Create a New Column

        Code

        import pandas as pd
        
        def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame:
            employees['bonus'] = employees['salary'] * 2
            return employees
        

        4.7.191 - 2025-08-21 18:17:05 +0300 MSK

        Select Data

        Code

        import pandas as pd
        
        def selectData(students: pd.DataFrame) -> pd.DataFrame:
            return students.loc[students["student_id"] == 101, ["name", "age"]]
        

        4.7.192 - 2025-08-21 18:16:46 +0300 MSK

        Display the First Three Rows

        Code

        import pandas as pd
        
        def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
            return employees.head(3)
        

        4.7.193 - 2025-08-21 18:16:25 +0300 MSK

        Get the Size of a DataFrame

        Code

        import pandas as pd
        
        def getDataframeSize(players: pd.DataFrame) -> List:
            return [players.shape[0], players.shape[1]]
        

        4.7.194 - 2025-08-21 18:16:06 +0300 MSK

        Create a DataFrame from List

        Code

        import pandas as pd
        
        def createDataframe(student_data: List[List[int]]) -> pd.DataFrame:
            column_names = ["student_id", "age"]
            result_dataframe = pd.DataFrame(student_data, columns=column_names)
            return result_dataframe
        

        4.7.195 - 2025-08-21 18:15:24 +0300 MSK

        Maximum Value of an Ordered Triplet I

        Code

        from typing import List
        
        class Solution:
            def maximumTripletValue(self, nums: List[int]) -> int:
                n = len(nums)
                if n < 3:
                    return 0
                left_max = [0] * n
                left_max[0] = nums[0]
                for i in range(1, n):
                    left_max[i] = max(left_max[i - 1], nums[i])
                right_max = [0] * n
                right_max[-1] = nums[-1]
                for i in reversed(range(1, n - 1)):
                    right_max[i] = max(right_max[i + 1], nums[i])
                ans = 0
                for i in range(1, n - 1):
                    left = left_max[i - 1]
                    right = right_max[i + 1]
                    ans = max(ans, (left - nums[i]) * right)
                return ans
        

        4.7.196 - 2025-08-21 17:56:20 +0300 MSK

        Minimum Operations to Collect Elements

        Code

        class Solution:
            def minOperations(self, nums: List[int], k: int) -> int:
                enc = [False] * (k + 1)
                res = 0
                rem = k
                for num in reversed(nums):
                    res += 1
                    if 1 <= num <= k and not enc[num]:
                        enc[num] = True
                        rem -= 1
                        if rem == 0:
                            return res
                raise Exception
        

        4.7.197 - 2025-08-21 17:51:03 +0300 MSK

        Minimum Right Shifts to Sort the Array

        Code

        class Solution:
            def minimumRightShifts(self, nums: List[int]) -> int:
                drop = -1
                for i, num in enumerate(nums[1:], 1):
                    if num > nums[i - 1]:
                        continue
                    if drop != -1:
                        return -1
                    drop = i
                if drop == -1:
                    return 0
                if nums[0] <= nums[-1]:
                    return -1
                return len(nums) - drop
        

        4.7.198 - 2025-08-21 17:41:49 +0300 MSK

        Points That Intersect With Cars

        Code

        class Solution:
            def numberOfPoints(self, nums: List[List[int]]) -> int:
                line = [0] * 102
                points_on_line = 0
                for start, end in nums:
                    line[start] += 1
                    line[end + 1] -= 1
                for i in range(1, 102):
                    line[i] += line[i - 1]
                    if line[i] != 0:
                        points_on_line += 1
                return points_on_line
        

        4.7.199 - 2025-08-21 17:35:46 +0300 MSK

        Check if Strings Can be Made Equal With Operations I

        Code

        class Solution:
            def canBeEqual(self, s1: str, s2: str) -> bool:
                freqs_even = [0] * 26
                freqs_odd = [0] * 26
                for i, (char1, char2) in enumerate(zip(s1, s2)):
                    if i % 2 == 0:
                        trg = freqs_even
                    else:
                        trg = freqs_odd
                    trg[ord(char1) - 97] += 1
                    trg[ord(char2) - 97] -= 1
                for freq1, freq2 in zip(freqs_even, freqs_odd):
                    if freq1 != 0 or freq2 != 0:
                        return False
                return True
        

        4.7.200 - 2025-08-21 17:31:03 +0300 MSK

        Furthest Point From Origin

        Code

        class Solution:
            def furthestDistanceFromOrigin(self, moves: str) -> int:
                cnt_left, cnt_right, cnt_any = 0, 0, 0
                for char in moves:
                    if char == "L":
                        cnt_left += 1
                    elif char == "R":
                        cnt_right += 1
                    else:
                        cnt_any += 1
                if cnt_right > cnt_left:
                    return cnt_right - cnt_left + cnt_any
                return cnt_left - cnt_right + cnt_any
        

        4.7.201 - 2025-08-21 17:26:29 +0300 MSK

        Check if a String Is an Acronym of Words

        Code

        class Solution:
            def isAcronym(self, words: List[str], s: str) -> bool:
                if len(words) != len(s):
                    return False
                for i in range(len(words)):
                    if words[i][0] != s[i]:
                        return False
                return True
        

        4.7.202 - 2025-08-21 17:15:57 +0300 MSK

        Max Pair Sum in an Array

        Code

        class Solution:
            def maxSum(self, nums: List[int]) -> int:
                freqs = [[] for _ in range(10)]
                for num in nums:
                    dig = 0
                    orig = num
                    while num > 0:
                        dig = max(dig, num % 10)
                        num //= 10
                    heapq.heappush(freqs[dig], -orig)
                res = -1
                for nms in freqs:
                    if len(nms) < 2:
                        continue
                    res = max(res, -(heapq.heappop(nms) + heapq.heappop(nms)))
                return res
        

        4.7.203 - 2025-08-21 17:07:52 +0300 MSK

        Split Strings by Separator

        Code

        class Solution:
            def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]:
                res = []
                cur = []
                for word in words:
                    for char in itertools.chain(word, separator):
                        if char != separator:
                            cur.append(char)
                        elif cur:
                            res.append("".join(cur))
                            cur.clear()
                return res
        

        4.7.204 - 2025-08-21 17:05:33 +0300 MSK

        Check if Array is Good

        Code

        class Solution:
            def isGood(self, nums: list[int]) -> bool:
                mx = max(nums)
                if len(nums) != mx + 1:
                    return False
                freqs = defaultdict(int)
                for num in nums:
                    freqs[num] += 1
                if freqs[mx] != 2:
                    return False
                for i in range(1, mx):
                    if freqs[i] != 1:
                        return False
                return True
        

        4.7.205 - 2025-08-21 17:00:40 +0300 MSK

        Sum of Squares of Special Elements

        Code

        class Solution:
            def sumOfSquares(self, nums: List[int]) -> int:
                n = len(nums)
                res = 0
                for i in range(1, int(math.sqrt(n)) + 1):
                    if n % i != 0:
                        continue
                    idx1, idx2 = i - 1, (n // i) - 1
                    res += nums[idx1] ** 2
                    if idx2 != idx1:
                        res += nums[idx2] ** 2
                return res
        

        4.7.206 - 2025-08-21 16:51:13 +0300 MSK

        Sum of Squares of Special Elements

        Code

        class Solution:
            def sumOfSquares(self, nums: List[int]) -> int:
                n = len(nums)
                res = 0
                for i in range(n):
                    if n % (i + 1) == 0:
                        res += nums[i] ** 2
                return res
        

        4.7.207 - 2025-08-21 16:50:01 +0300 MSK

        Find the Maximum Achievable Number

        Code

        class Solution:
            def theMaximumAchievableX(self, num: int, t: int) -> int:
                return num + (t * 2) 
        

        4.7.208 - 2025-08-21 16:46:44 +0300 MSK

        Longest Alternating Subarray

        Code

        class Solution:
            def alternatingSubarray(self, nums: list[int]) -> int:
                n = len(nums)
                maxi = 0
                for i in range(n - 1):
                    if nums[i + 1] != nums[i] + 1:
                        continue
                    curr, prev = 2, 1
                    for j in range(i + 2, n):
                        diff = nums[j] - nums[j - 1]
                        if diff == -prev:
                            curr += 1
                            prev = -prev
                        else:
                            break
                    maxi = max(maxi, curr)
                return maxi if maxi > 0 else -1
        

        4.7.209 - 2025-08-21 16:44:37 +0300 MSK

        Longest Even Odd Subarray With Threshold

        Code

        class Solution:
            def longestAlternatingSubarray(self, nums: list[int], threshold: int) -> int:
                n = len(nums)
                if n == 1:
                    if nums[0] % 2 == 0 and nums[0] <= threshold:
                        return 1
                    return 0
                length = 0
                for l in range(n):
                    if nums[l] % 2 != 0:
                        continue
                    for r in range(l, n):
                        if nums[r] > threshold:
                            break
                        ok = True
                        for i in range(l, r):
                            if nums[i] % 2 == nums[i + 1] % 2:
                                ok = False
                                break
                        if ok:
                            length = max(length, r - l + 1)
                return length
        

        4.7.210 - 2025-08-21 16:42:44 +0300 MSK

        Number of Beautiful Pairs

        Code

        class Solution:
            def countBeautifulPairs(self, nums: List[int]) -> int:
                def check(num1: int, num2: int) -> bool: 
                    first, last = 0, num2 % 10
                    while num1 > 0:
                        first = num1 % 10
                        num1 //= 10
                    return math.gcd(first, last) == 1
                res = 0
                for i in range(len(nums)):
                    for j in range(i + 1, len(nums)):
                        if check(nums[i], nums[j]):
                            res += 1
                return res
        

        4.7.211 - 2025-08-21 16:38:20 +0300 MSK

        Find Maximum Number of String Pairs

        Code

        class Solution:
            def maximumNumberOfStringPairs(self, words: List[str]) -> int:
                enc = set()
                res = 0
                for word in words:
                    if word in enc:
                        res += 1
                    else:
                        enc.add(word[::-1])
                return res
        

        4.7.212 - 2025-08-21 16:26:55 +0300 MSK

        Total Distance Traveled

        Code

        class Solution:
            def distanceTraveled(self, mainTank: int, additionalTank: int) -> int:
                res = 0
                while mainTank > 4:
                    count = mainTank // 5
                    res += count * 5
                    mainTank %= 5
                    add_count = min(count, additionalTank)
                    additionalTank -= add_count
                    mainTank += add_count
                res += mainTank
                return res * 10
        

        4.7.213 - 2025-08-21 16:19:42 +0300 MSK

        Neither Minimum nor Maximum

        Code

        class Solution:
            def findNonMinOrMax(self, nums: List[int]) -> int:
                nums.sort()
                min_val, max_val = nums[0], nums[-1]
                if nums[0] == nums[-1]:
                    return -1
                if len(nums) < 3:
                    return -1
                left, right = 0, len(nums) - 1
                while left <= right:
                    mid = left + (right - left) // 2
                    val = nums[mid]
                    if val == min_val:
                        left = mid + 1
                    elif val == max_val:
                        right = mid - 1
                    return val
                return -1
        

        4.7.214 - 2025-08-21 16:16:56 +0300 MSK

        Check if The Number is Fascinating

        Code

        class Solution:
            def isFascinating(self, n: int) -> bool:
                freqs = [False] * 9
                for num in (n, n * 2, n * 3):
                    while num > 0:
                        dig = num % 10
                        if dig == 0:
                            return False
                        if freqs[dig - 1]:
                            return False
                        freqs[dig - 1] = True
                        num //= 10
                return sum(freqs) == 9
        

        4.7.215 - 2025-08-21 16:07:01 +0300 MSK

        Is Object Empty

        Code

        /**
         * @param {Object|Array} obj
         * @return {boolean}
         */
        var isEmpty = function(obj) {
            if (Array.isArray(obj)) {
                return obj.length === 0;
            } else {
                return Object.keys(obj).length === 0;
            }
        };
        

        4.7.216 - 2025-08-21 16:06:09 +0300 MSK

        Calculator with Method Chaining

        Code

        class Calculator {
            
            /** 
             * @param {number} value
             */
            constructor(value) {
                this.result = value 
            }
            
            /** 
             * @param {number} value
             * @return {Calculator}
             */
            add(value){
                this.result += value 
                return this 
            }
            
            /** 
             * @param {number} value
             * @return {Calculator}
             */
            subtract(value){
                this.result -= value 
                return this 
            }
            
            /** 
             * @param {number} value
             * @return {Calculator}
             */  
            multiply(value) {
                this.result *= value 
                return this 
            }
            
            /** 
             * @param {number} value
             * @return {Calculator}
             */
            divide(value) {
        
           if(value === 0){
             throw new Error("Division by zero is not allowed")
                }
                this.result /= value 
                return this 
            }
            
            /** 
             * @param {number} value
             * @return {Calculator}
             */
            power(value) {
                this.result **= value 
                return this 
            }
            
            /** 
             * @return {number}
             */
            getResult() {
                return this.result 
            }
        }
        

        4.7.217 - 2025-08-21 16:01:02 +0300 MSK

        Interval Cancellation

        Code

        /**
         * @param {Function} fn
         * @param {Array} args
         * @param {number} t
         * @return {Function}
         */
        var cancellable = function(fn, args, t) {
            fn(...args);
            const timer = setInterval(() => fn(...args), t);
            const cancelFn = () => clearInterval(timer);
            return cancelFn;
        };
        
        /**
         *  const result = [];
         *
         *  const fn = (x) => x * 2;
         *  const args = [4], t = 35, cancelTimeMs = 190;
         *
         *  const start = performance.now();
         *
         *  const log = (...argsArr) => {
         *      const diff = Math.floor(performance.now() - start);
         *      result.push({"time": diff, "returned": fn(...argsArr)});
         *  }
         *       
         *  const cancel = cancellable(log, args, t);
         *
         *  setTimeout(cancel, cancelTimeMs);
         *   
         *  setTimeout(() => {
         *      console.log(result); // [
         *                           //     {"time":0,"returned":8},
         *                           //     {"time":35,"returned":8},
         *                           //     {"time":70,"returned":8},
         *                           //     {"time":105,"returned":8},
         *                           //     {"time":140,"returned":8},
         *                           //     {"time":175,"returned":8}
         *                           // ]
         *  }, cancelTimeMs + t + 15)    
         */
        

        4.7.218 - 2025-08-21 15:58:36 +0300 MSK

        Sort By

        Code

        /**
         * @param {Array} arr
         * @param {Function} fn
         * @return {Array}
         */
        var sortBy = function(arr, fn) {
            return arr.toSorted((a, b) => fn(a) - fn(b));
        };
        

        4.7.219 - 2025-08-21 15:55:14 +0300 MSK

        Add Two Promises

        Code

        /**
         * @param {Promise} promise1
         * @param {Promise} promise2
         * @return {Promise}
         */
        var addTwoPromises = async function(promise1, promise2) {
            const [value1, value2] = await Promise.all([promise1, promise2]);
            return value1 + value2;
        };
        
        // // Example usage:
        // var promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20));
        // var promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60));
        
        // addTwoPromises(promise1, promise2)
        //   .then(console.log); // Output: 7
        

        4.7.220 - 2025-08-21 15:49:02 +0300 MSK

        Semi-Ordered Permutation

        Code

        class Solution:
            def semiOrderedPermutation(self, nums: List[int]) -> int:
                i1, i2 = 0, 0
                n = len(nums)
                for i, num in enumerate(nums):
                    if num == 1:
                        i1 = i
                    elif num == n:
                        i2 = i
                    if i1 and i2:
                        break
                res = i1 + (n - i2 - 1)
                if i2 < i1:
                    res -= 1
                return res
        

        4.7.221 - 2025-08-21 15:45:35 +0300 MSK

        Minimize String Length

        Code

        class Solution:
            def minimizedStringLength(self, s: str) -> int:
                freqs = [False] * 26
                for char in s:
                    freqs[ord(char) - 97] = True
                return sum(freqs)
        

        4.7.222 - 2025-08-21 15:42:45 +0300 MSK

        Timeout Cancellation

        Code

        /**
         * @param {Function} fn
         * @param {Array} args
         * @param {number} t
         * @return {Function}
         */
        const cancellable = function(fn, args, t) {
            const timer = setTimeout(() => {
                fn(...args)
            }, t);
            const cancelFn = function() {
                clearTimeout(timer);
            };
            return cancelFn;
        };
        
        
        /**
         *  const result = []
         *
         *  const fn = (x) => x * 5
         *  const args = [2], t = 20, cancelT = 50
         *
         *  const log = (...argsArr) => {
         *      result.push(fn(...argsArr))
         *  }
         *       
         *  const cancel = cancellable(fn, args, t);
         *           
         *  setTimeout(() => {
         *     cancel()
         *     console.log(result) // [{"time":20,"returned":10}]
         *  }, cancelT)
         */
        

        4.7.223 - 2025-08-21 15:40:49 +0300 MSK

        Remove Trailing Zeros From a String

        Code

        class Solution:
            def removeTrailingZeros(self, num: str) -> str:
                val = int(num)
                while val > 0 and val % 10 == 0:
                    val //= 10
                return str(val)
        

        4.7.224 - 2025-08-21 15:37:36 +0300 MSK

        To Be Or Not To Be

        Code

        class Check {
            constructor(val) {
                this.val = val;
            }
            toBe(val) {
                if (val === this.val) {
                    return true;
                }
                throw new Error("Not Equal");
            }
            notToBe(val) {
                if (val !== this.val) {
                    return true;
                }
                throw new Error("Equal");
            }
        }
        
        /**
         * @param {string} val
         * @return {Object}
         */
        var expect = function(val) {
            return new Check(val);  
        };
        
        /**
         * expect(5).toBe(5); // true
         * expect(5).notToBe(5); // throws "Equal"
         */
        

        4.7.225 - 2025-08-21 15:33:15 +0300 MSK

        Return Length of Arguments Passed

        Code

        /**
         * @param {...(null|boolean|number|string|Array|Object)} args
         * @return {number}
         */
        var argumentsLength = function(...args) {
            return args.length;
        };
        
        /**
         * argumentsLength(1, 2, 3); // 3
         */
        

        4.7.226 - 2025-08-21 15:32:49 +0300 MSK

        Lexicographically Smallest Palindrome

        Code

        class Solution:
            def makeSmallestPalindrome(self, s: str) -> str:
                letters = list(s)
                for i in range(len(s) // 2):
                    letters[i] = letters[~i] = min(letters[i], letters[~i])
                return ''.join(letters)
        

        4.7.227 - 2025-08-21 15:03:03 +0300 MSK

        Minimum String Length After Removing Substrings

        Code

        class Solution:
            def minLength(self, s: str) -> int:
                stack = []
                for char in s:
                    if not stack or char not in "ABCD":
                        stack.append(char)
                        continue
                    if (
                        (stack[-1] == "A" and char == "B") 
                        or (stack[-1] == "C" and char == "D")
                    ):
                        stack.pop()
                    else:
                        stack.append(char)
                return len(stack)
        

        4.7.228 - 2025-08-21 14:57:54 +0300 MSK

        Minimum String Length After Removing Substrings

        Code

        class Solution:
            def minLength(self, s: str) -> int:
                while "AB" in s or "CD" in s:
                    s = s.replace("AB", "").replace("CD", "")
                return len(s)
        

        4.7.229 - 2025-08-21 14:56:18 +0300 MSK

        Array Wrapper

        Code

        /**
         * @param {number[]} nums
         * @return {void}
         */
        var ArrayWrapper = function(nums) {
            this.sum = nums.reduce((a, b) => a + b, 0);
            this.string = `[${nums.toString()}]`;
        };
        
        /**
         * @return {number}
         */
        ArrayWrapper.prototype.valueOf = function() {
            return this.sum;
        }
        
        /**
         * @return {string}
         */
        ArrayWrapper.prototype.toString = function() {
            return this.string;
        }
        
        /**
         * const obj1 = new ArrayWrapper([1,2]);
         * const obj2 = new ArrayWrapper([3,4]);
         * obj1 + obj2; // 10
         * String(obj1); // "[1,2]"
         * String(obj2); // "[3,4]"
         */
        

        4.7.230 - 2025-08-21 14:52:44 +0300 MSK

        Find the Losers of the Circular Game

        Code

        class Solution:
            def circularGameLosers(self, n: int, k: int) -> List[int]:
                count = 1
                i = 0
                enc = set((0, ))
                while True:
                    i = (i + k * count) % n
                    if i in enc:
                        break
                    enc.add(i)
                    count += 1
                res = []
                for i in range(n):
                    if i not in enc:
                        res.append(i + 1)
                return res
        

        4.7.231 - 2025-08-21 14:47:10 +0300 MSK

        Number of Senior Citizens

        Code

        class Solution:
            def countSeniors(self, details: List[str]) -> int:
                count = 0
                for detail in details:
                    if int(detail[-4:-2]) > 60:
                        count += 1
                return count
        

        4.7.232 - 2025-08-21 14:44:56 +0300 MSK

        Chunk Array

        Code

        /**
         * @param {Array} arr
         * @param {number} size
         * @return {Array}
         */
        var chunk = function(arr, size) {
            const chunkedArray = [];
            let index = 0;
            while (index < arr.length) {
                chunkedArray.push(arr.slice(index, index + size));
                index += size;
            }
            return chunkedArray;
        };
        

        4.7.233 - 2025-08-21 14:42:42 +0300 MSK

        Find the Distinct Difference Array

        Code

        class Solution:
            def distinctDifferenceArray(self, nums: List[int]) -> List[int]:
                left, right = set(), defaultdict(int)
                for num in nums:
                    right[num] += 1
                res = []
                for num in nums:
                    left.add(num)
                    right[num] -= 1
                    if right[num] == 0:
                        del right[num]
                    res.append(len(left) - len(right))
                return res
        

        4.7.234 - 2025-08-21 14:32:28 +0300 MSK

        Create Hello World Function

        Code

        /**
         * @return {Function}
         */
        var createHelloWorld = function() {
            
            return function(...args) {
                return "Hello World";
            }
        };
        
        /**
         * const f = createHelloWorld();
         * f(); // "Hello World"
         */
        

        4.7.235 - 2025-08-21 14:31:55 +0300 MSK

        Allow One Function Call

        Code

        /**
         * @param {Function} fn
         * @return {Function}
         */
        var once = function(fn) {
            let called = false;
            return function(...args){
                if (called) {
                    return undefined;
                }
                called = true;
                return fn(...args);
            }
        };
        
        /**
         * let fn = (a,b,c) => (a + b + c)
         * let onceFn = once(fn)
         *
         * onceFn(1,2,3); // 6
         * onceFn(2,3,6); // returns undefined without calling fn
         */
        

        4.7.236 - 2025-08-21 14:30:46 +0300 MSK

        Counter II

        Code

        class Counter {
            constructor(init) {
                this.init = init;
                this.val = init;
            }
            increment() {
                let val = this.val + 1;
                this.val = val;
                return val;
            }
            decrement() {
                let val = this.val - 1;
                this.val = val;
                return val;
            }
            reset() {
                let val = this.init;
                this.val = val;
                return val;
            }
        }
        
        /**
         * @param {integer} init
         * @return { increment: Function, decrement: Function, reset: Function }
         */
        var createCounter = function(init) {
            return new Counter(init)
        };
        
        /**
         * const counter = createCounter(5)
         * counter.increment(); // 6
         * counter.reset(); // 5
         * counter.decrement(); // 4
         */
        

        4.7.237 - 2025-08-21 14:28:11 +0300 MSK

        Determine the Winner of a Bowling Game

        Code

        class Solution:
            def isWinner(self, player1: List[int], player2: List[int]) -> int:
                last_10_1, last_10_2 = -10, -10
                score = 0
                for i, (hit1, hit2) in enumerate(zip(player1, player2)):
                    mult1, mult2 = 1, 1
                    if i - last_10_1 < 3:
                        mult1 = 2
                    if i - last_10_2 < 3:
                        mult2 = 2
                    score += hit1 * mult1 - hit2 * mult2
                    if hit1 == 10:
                        last_10_1 = i
                    if hit2 == 10:
                        last_10_2 = i
                if score > 0:
                    return 1
                elif score < 0:
                    return 2
                return 0
        

        4.7.238 - 2025-08-21 14:14:45 +0300 MSK

        Maximum Sum With Exactly K Elements

        Code

        class Solution:
            def maximizeSum(self, nums: List[int], k: int) -> int:
                first = max(nums)
                last = first + (k - 1) * 1
                return (k * (first + last)) // 2
        

        4.7.239 - 2025-08-21 14:03:34 +0300 MSK

        Sum Multiples

        Code

        class Solution:
            def sumOfMultiples(self, n: int) -> int:
                enc = set()
                for num in range(3, n + 1, 3):
                    enc.add(num)
                for num in range(5, n + 1, 5):
                    enc.add(num)
                for num in range(7, n + 1, 7):
                    enc.add(num)
                return sum(enc)
        

        4.7.240 - 2025-08-21 13:59:45 +0300 MSK

        Calculate Delayed Arrival Time

        Code

        class Solution:
            def findDelayedArrivalTime(self, arrivalTime: int, delayedTime: int) -> int:
                return (arrivalTime + delayedTime) % 24
        

        4.7.241 - 2025-08-21 13:58:37 +0300 MSK

        Generate Fibonacci Sequence

        Code

        /**
         * @return {Generator<number>}
         */
        var fibGenerator = function*() {
            let num1 = 0;
            let num2 = 1;
            yield num1;
            yield num2;
            while (true) {
                const num3 = num1 + num2;
                num1 = num2;
                num2 = num3;
                yield num3; 
            }
        };
        
        /**
         * const gen = fibGenerator();
         * gen.next().value; // 0
         * gen.next().value; // 1
         */
        

        4.7.242 - 2025-08-21 13:56:09 +0300 MSK

        Find the Maximum Divisibility Score

        Code

        class Solution:
            def maxDivScore(self, nums: List[int], divisors: List[int]) -> int:
                freqs = defaultdict(int)
                for num in nums:
                    freqs[num] += 1
                divisors.sort()
                max_div, max_count = divisors[0], 0
                for div in divisors:
                    count = 0
                    for num, freq in freqs.items():
                        if num % div == 0:
                            count += freq
                    if count > max_count:
                        max_div, max_count = div, count
                return max_div
        

        4.7.243 - 2025-08-21 13:42:53 +0300 MSK

        Row With Maximum Ones

        Code

        class Solution:
            def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
                max_row, max_count = 0, sum(mat[0])
                for i, row in enumerate(mat[1:], 1):
                    count = sum(row)
                    if count > max_count:
                        max_row, max_count = i, count
                return max_row, max_count
        

        4.7.244 - 2025-08-21 13:40:48 +0300 MSK

        Find the Width of Columns of a Grid

        Code

        class Solution:
            def findColumnWidth(self, grid: List[List[int]]) -> List[int]:
                res = []
                for col in range(len(grid[0])):
                    max_len = 0
                    for row in range(len(grid)):
                        val = grid[row][col]
                        if val == 0:
                            count = 1
                        elif val < 0:
                            count = 1
                            val = -val
                        else:
                            count = 0
                        while val > 0:
                            count += 1
                            val //= 10
                        max_len = max(max_len, count)
                    res.append(max_len)
                return res
        

        4.7.245 - 2025-08-21 13:31:24 +0300 MSK

        Range Sum Query - Mutable

        Code

        class TreeNode:
            def __init__(self, val, start, end, left_child = None, right_child = None):
                self.val = val
                self.start = start
                self.end = end
                self.left_child = left_child
                self.right_child = right_child
                
        class SegmentTree:
            def __init__(self, nums):
                self.nums = nums
                self.root = self.build(0, len(nums) - 1)
            
            def build(self, start, end):
                if start == end:
                    return TreeNode(self.nums[start], start, end)
                left_child = self.build(start, (start + end) //2)
                right_child = self.build((start+end) // 2 + 1, end)
                return TreeNode(left_child.val + right_child.val, start, end, left_child, right_child)
            
            def update(self, root, index, value):
                if root.start == root.end and index == root.start: # target
                    root.val = value
                    return value
                if root.start > index or root.end < index:
                    return root.val
                root.val = self.update(root.left_child, index, value) + self.update(root.right_child, index, value)
                return root.val
        
            def query(self, root, left, right):
                if root.start > right or root.end < left: return 0
                if root.start >= left and root.end <= right: return root.val
                return self.query(root.left_child, left, right) + self.query(root.right_child, left, right)
        
        class NumArray:
            def __init__(self, nums: List[int]):
                self.tree = SegmentTree(nums)
                self.root = self.tree.root
        
            def update(self, index: int, val: int) -> None:
                self.tree.update(self.root, index, val)
        
            def sumRange(self, left: int, right: int) -> int:
                return self.tree.query(self.root, left, right)
        

        4.7.246 - 2025-08-21 13:26:07 +0300 MSK

        Online Election

        Code

        class TopVotedCandidate:
        
            def __init__(self, persons: List[int], times: List[int]):
                self._lead = times
                freqs = [0] * 5001
                prev = persons[0]
                freqs[prev] = 1
                times[0] = (times[0], prev)
                for i in range(1, len(times)):
                    person = persons[i]
                    freq = freqs[person] + 1
                    freqs[person] = freq
                    if freq >= freqs[prev]:
                        prev = person
                    times[i] = (times[i], prev)
                
            def q(self, t: int) -> int:
                left, right = 0, len(self._lead) - 1
                res = None
                while left <= right:
                    mid = left + (right - left) // 2
                    lead_time, lead_person = self._lead[mid]
                    if lead_time > t:
                        right = mid - 1
                    elif lead_time == t:
                        return lead_person
                    else:
                        res = lead_person
                        left = mid + 1
                return res
        
        
        # Your TopVotedCandidate object will be instantiated and called as such:
        # obj = TopVotedCandidate(persons, times)
        # param_1 = obj.q(t)
        

        4.7.247 - 2025-08-21 12:41:54 +0300 MSK

        Walking Robot Simulation II

        Code

        class Robot:
        
            def __init__(self, width: int, height: int):
                self.cur = (0, 0)
                self.cur_dir = 0
                self.width = width
                self.height = height
                self.dir_mapping = {
                    0: "East",
                    1: "North",
                    2: "West",
                    3: "South"
                }
                self.mod = 2 * (self.width + self.height - 2)
        
            def step(self, num: int) -> None:
                if num >= self.mod:
                    num %= self.mod
                    if self.cur == (0, 0) and self.cur_dir == 0:
                        self.cur_dir = 3
                row, col = self.cur
                while num > 0:
                    if self.cur_dir == 0:
                        steps = min(num, self.width - row -1)
                        num -= steps
                        row += steps
                    elif self.cur_dir == 1:
                        steps = min(num, self.height -1 - col)
                        num -= steps
                        col += steps
                    elif self.cur_dir == 2:
                        steps = min(num, row)
                        num -= steps
                        row -= steps
                    else:
                        steps = min(num, col)
                        num -= steps
                        col -= steps
                    if num > 0:
                        self.cur_dir = (self.cur_dir + 1) % 4
                self.cur = row, col
        
            def getPos(self) -> List[int]:
                return self.cur
        
            def getDir(self) -> str:
                return self.dir_mapping[self.cur_dir]
        
        # Your Robot object will be instantiated and called as such:
        # obj = Robot(width, height)
        # obj.step(num)
        # param_2 = obj.getPos()
        # param_3 = obj.getDir()
        

        4.7.248 - 2025-08-21 12:07:22 +0300 MSK

        Number of Beautiful Integers in the Range

        Code

        class Solution:
            def numberOfBeautifulIntegers(self, low: int, high: int, k: int) -> int:
                low, hgh = str(low), str(high)  
                n = len(hgh)                    
                low = low.rjust(n,'0')          
                @lru_cache(None)
                def dfs(idx,
                        belowHgh,                
                        aboveLow,                
                        init0,
                        parity,
                        rem):                    
                    if idx == n: 
                        return rem == 0 == parity  
                    lowD, hghD = int(low[idx]), int(hgh[idx])
                    res = 0
                    for digit in range(0 if aboveLow else lowD,
                                       (9 if belowHgh else hghD) + 1):
                        res += dfs(idx + 1,
                                   belowHgh or digit < hghD,
                                   aboveLow or digit > lowD,
                                   init0 and not digit,
                                   parity + digit % 2 - (
                                            not init0 and not digit or
                                            digit and not digit % 2),
                                   (rem * 10 + digit) % k)
                    return res
                return dfs(0, False, False, True, 0, 0)
        

        4.7.249 - 2025-08-21 11:45:30 +0300 MSK

        Minimum Seconds to Equalize a Circular Array

        Code

        class Solution:
            def minimumSeconds(self, nums: List[int]) -> int:
                nums += nums
                indices = defaultdict(list)
                for i, num in enumerate(nums):
                    indices[num].append(i)
                min_diff = math.inf
                for idxs in indices.values():
                    max_diff = -math.inf
                    for i1, i2 in itertools.pairwise(idxs):
                        max_diff = max(max_diff, i2 - i1)
                    min_diff = min(min_diff, max_diff // 2)
                return min_diff
        

        4.7.250 - 2025-08-21 11:32:12 +0300 MSK

        Longest Arithmetic Subsequence of Given Difference

        Code

        class Solution:
            def longestSubsequence(self, arr: List[int], difference: int) -> int:
                dp = {}
                for num in arr:
                    prv = num - difference 
                    if prv in dp:
                        dp[num] = dp[prv] + 1
                    else:
                        dp[num] = 1
                return max(dp.values())
        

        4.7.251 - 2025-08-21 11:29:38 +0300 MSK

        Longest Arithmetic Subsequence of Given Difference

        Code

        class Solution:
            def longestSubsequence(self, arr: List[int], difference: int) -> int:
                n = len(arr)
                freqs = defaultdict(list)
                for i, num in enumerate(arr):
                    freqs[num].append(i)
                dp = [1] * n
                for i in reversed(range(n - 1)):
                    cur, nxt = arr[i], arr[i] + difference
                    if nxt not in freqs:
                        continue
                    cnt = 0
                    for j in freqs[nxt]:
                        if j > i:
                            cnt = max(cnt, dp[j])
                    dp[i] = cnt + 1
                return max(dp)
        

        4.7.252 - 2025-08-21 11:16:33 +0300 MSK

        Shortest String That Contains Three Strings

        Code

        class Solution:
            def minimumString(self, a: str, b: str, c: str) -> str:
                res, l = '', float('inf')
                def merge(s1: str, s2: str) -> str:
                    if s2 in s1:
                        return s1
                    for i in range(len(s1)):
                        if s2.startswith(s1[i:]):
                            return s1[:i] + s2
                    return s1 + s2
                for s1, s2, s3 in itertools.permutations((a, b ,c)): 
                    merged = merge(merge(s1, s2), s3)
                    if len(merged) < l:
                        res, l = merged, len(merged)
                    elif len(merged) == l:
                        res = min(res, merged)
                return res
        

        4.7.253 - 2025-08-21 11:08:30 +0300 MSK

        Design Neighbor Sum Service

        Code

        class NeighborSum:
        
            def __init__(self, grid: List[List[int]]):
                self._adj = [0] * 101
                self._diag = [0] * 101
                rows, cols = len(grid), len(grid[0])
                adj_moves = ((0, 1), (0, -1), (-1, 0), (1, 0))
                diag_moves = ((-1, -1), (-1, 1), (1, -1), (1, 1))
                for row in range(rows):
                    for col in range(cols):
                        val = grid[row][col]
                        for row_dlt, col_dlt in adj_moves:
                            adj_row, adj_col = row + row_dlt, col + col_dlt
                            if 0 <= adj_row < rows and 0 <= adj_col < cols:
                                self._adj[grid[adj_row][adj_col]] += val
                        for row_dlt, col_dlt in diag_moves:
                            diag_row, diag_col = row + row_dlt, col + col_dlt
                            if 0 <= diag_row < rows and 0 <= diag_col < cols:
                                self._diag[grid[diag_row][diag_col]] += val
        
            def adjacentSum(self, value: int) -> int:
                return self._adj[value]
        
            def diagonalSum(self, value: int) -> int:
                return self._diag[value]
        
        
        # Your NeighborSum object will be instantiated and called as such:
        # obj = NeighborSum(grid)
        # param_1 = obj.adjacentSum(value)
        # param_2 = obj.diagonalSum(value)
        

        4.7.254 - 2025-08-21 08:52:21 +0300 MSK

        Count Submatrices With All Ones

        Code

        class Solution:
            def numSubmat(self, mat: List[List[int]]) -> int:
                heights = [0] * len(mat[0])
                res = 0
                for row in mat:
                    for i, x in enumerate(row):
                        heights[i] = 0 if x == 0 else heights[i] + 1
                    stack = [[-1, 0, -1]]
                    for i, h in enumerate(heights):
                        while stack[-1][2] >= h:
                            stack.pop()
                        j, prev, _ = stack[-1]
                        cur = prev + (i - j) * h
                        stack.append([i, cur, h])
                        res += cur
                return res
        

        4.7.255 - 2025-08-20 20:41:08 +0300 MSK

        Apply Transform Over Each Element in Array

        Code

        /**
         * @param {number[]} arr
         * @param {Function} fn
         * @return {number[]}
         */
        var map = function(arr, fn) {
          const transformedArr = [];
          let index = 0;
          for (const element of arr) {
            transformedArr[index] = fn(element, index);
            index++;
          }
          return transformedArr;
        };
        

        4.7.256 - 2025-08-20 20:38:27 +0300 MSK

        Filter Elements from Array

        Code

        /**
         * @param {number[]} arr
         * @param {Function} fn
         * @return {number[]}
         */
        var filter = function(arr, fn) {
            let res = [];
            for (const [i, val] of arr.entries()) {
                if (fn(val, i)) {
                    res.push(val);
                }
            }
            return res;
        };
        

        4.7.257 - 2025-08-20 20:36:18 +0300 MSK

        Function Composition

        Code

        /**
         * @param {Function[]} functions
         * @return {Function}
         */
        var compose = function(functions) {
        	if (functions.length === 0) {
                return function(x) { return x; };
            }
            return functions.reduceRight(function(prevFn, nextFn) {
                return function(x) {
                    return nextFn(prevFn(x));
                };
            });
        };
        

        4.7.258 - 2025-08-20 20:31:33 +0300 MSK

        Array Reduce Transformation

        Code

        /**
         * @param {number[]} nums
         * @param {Function} fn
         * @param {number} init
         * @return {number}
         */
        var reduce = function(nums, fn, init) {
            let res = init;
            for (const num of nums) {
                res = fn(res, num);
            }
            return res;
        };
        

        4.7.259 - 2025-08-20 20:28:21 +0300 MSK

        Sleep

        Code

        /**
         * @param {number} millis
         * @return {Promise}
         */
        async function sleep(millis) {
            return new Promise((resolve) => setTimeout(resolve, millis));   
        }
        
        /** 
         * let t = Date.now()
         * sleep(100).then(() => console.log(Date.now() - t)) // 100
         */
        

        4.7.260 - 2025-08-20 20:26:57 +0300 MSK

        Counter

        Code

        /**
         * @param {number} n
         * @return {Function} counter
         */
        var createCounter = function(n) {
            val = n - 1;
            return function() {
                val += 1;
                return val;
            };
        };
        
        /** 
         * const counter = createCounter(10)
         * counter() // 10
         * counter() // 11
         * counter() // 12
         */
        

        4.7.261 - 2025-08-20 20:25:45 +0300 MSK

        Array Prototype Last

        Code

        /**
         * @return {null|boolean|number|string|Array|Object}
         */
        Array.prototype.last = function() {
            if (this.length > 0) {
                return this[this.length - 1];
            }
            return -1;
        };
        
        /**
         * const arr = [1, 2, 3];
         * arr.last(); // 3
         */
        

        4.7.262 - 2025-08-20 20:20:02 +0300 MSK

        Prime In Diagonal

        Code

        class Solution:
            def diagonalPrime(self, nums: List[List[int]]) -> int:
                def is_prime(num: int) -> int:
                    if num <= 1:
                        return 0
                    for i in range(2, int(math.sqrt(num)) + 1):
                        if num % i == 0:
                            return 0
                    return num
                res = 0
                n = len(nums)
                for i in range(n):
                    res = max(res, is_prime(nums[i][i]), is_prime(nums[i][n - i - 1]))
                return res
        

        4.7.263 - 2025-08-20 20:15:03 +0300 MSK

        Find the Longest Balanced Substring of a Binary String

        Code

        class Solution:
            def findTheLongestBalancedSubstring(self, s: str) -> int:
                res = 0
                cnt_0, cnt_1 = 0, 0
                for char in s:
                    if char == "0":
                        if cnt_1 != 0:
                            cnt_0 = 0
                        cnt_0 += 1
                        cnt_1 = 0
                    else:
                        cnt_1 += 1
                        res = max(res, min(cnt_0, cnt_1) * 2)
                return res
        

        4.7.264 - 2025-08-20 20:10:18 +0300 MSK

        Form Smallest Number From Two Digit Arrays

        Code

        class Solution:
            def minNumber(self, nums1: List[int], nums2: List[int]) -> int:
                freqs1 = [False] * 10
                freqs2 = [False] * 10
                for num in nums1:
                    freqs1[num] = True
                for num in nums2:
                    freqs2[num] = True
                min1, min2 = None, None
                for i in range(10):
                    if freqs1[i] and freqs2[i]:
                        return i
                    if min1 is None and freqs1[i]:
                        min1 = i
                    if min2 is None and freqs2[i]:
                        min2 = i
                return min(min1, min2) * 10 + max(min1, min2) 
                
        

        4.7.265 - 2025-08-20 19:48:54 +0300 MSK

        K Items With the Maximum Sum

        Code

        class Solution:
            def kItemsWithMaximumSum(self, numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int:
                res = 0
                for val, cnt in ((1, numOnes), (0, numZeros), (-1, numNegOnes)):
                    if k == 0:
                        break
                    cnt = min(k, cnt)
                    k -= cnt
                    res += val * cnt
                return res
        

        4.7.266 - 2025-08-20 19:41:49 +0300 MSK

        Distribute Money to Maximum Children

        Code

        class Solution:
            def distMoney(self, money: int, children: int) -> int:
                if money < children: 
                    return -1 
                n = 8 * children - money
                if n <= 0: 
                    return children - (n < 0)
                ans, rem = divmod(money - children, 7)
                return ans - ((ans, rem) == (children - 1, 3))
        

        4.7.267 - 2025-08-20 19:24:46 +0300 MSK

        Count the Number of Vowel Strings in Range

        Code

        class Solution:
            def vowelStrings(self, words: List[str], left: int, right: int) -> int:
                res = 0
                vowels = ("a", "e", "i", "o", "u")
                for i in range(left, right + 1):
                    word = words[i]
                    if word[0] in vowels and word[-1] in vowels:
                        res += 1
                return res
        

        4.7.268 - 2025-08-20 19:22:34 +0300 MSK

        Pass the Pillow

        Code

        class Solution:
            def passThePillow(self, n, time):
                full_rounds = time // (n - 1)
                extra_time = time % (n - 1)
                if full_rounds % 2 == 0:
                    return extra_time + 1
                else:
                    return n - extra_time
        

        4.7.269 - 2025-08-20 19:11:13 +0300 MSK

        Split With Minimum Sum

        Code

        class Solution:
            def splitNum(self, num: int) -> int:
                count = 0
                digits = []
                while num > 0:
                    digits.append(num % 10)
                    num //= 10
                digits.sort()
                res = 0
                while digits:
                    for _ in range(2):
                        if digits:    
                            res += digits.pop() * (10 ** count)
                    count += 1
                return res
        

        4.7.270 - 2025-08-20 19:07:59 +0300 MSK

        Left and Right Sum Differences

        Code

        class Solution:
            def leftRightDifference(self, nums: List[int]) -> List[int]:
                left, right = 0, sum(nums)
                for i in range(len(nums)):
                    val = nums[i]
                    right -= val
                    nums[i] = abs(left - right)
                    left += val
                return nums
        

        4.7.271 - 2025-08-20 19:05:44 +0300 MSK

        Merge Two 2D Arrays by Summing Values

        Code

        class Solution:
            def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:
                freqs = [0] * 1001
                for idx, val in itertools.chain(nums1, nums2):
                    freqs[idx] += val
                res = []
                for i, freq in enumerate(freqs):
                    if freq > 0:
                        res.append((i, freq))
                return res
        

        4.7.272 - 2025-08-20 19:01:55 +0300 MSK

        Maximum Difference by Remapping a Digit

        Code

        class Solution:
            def minMaxDifference(self, num: int) -> int:
                s = str(num)
                t = s
                pos = 0
                while pos < len(s) and s[pos] == "9":
                    pos += 1
                if pos < len(s):
                    s = s.replace(s[pos], "9")
                t = t.replace(t[0], "0")
                return int(s) - int(t)
        

        4.7.273 - 2025-08-20 18:54:48 +0300 MSK

        Find the Array Concatenation Value

        Code

        class Solution:
            def findTheArrayConcVal(self, nums: List[int]) -> int:
                def concat(num1: int, num2: int) -> int:
                    res = 0
                    count = 0
                    for num in (num2, num1):
                        while num > 0:
                            res += (num % 10) * (10 ** count)
                            count += 1
                            num //= 10
                    return res
                left, right = 0, len(nums) - 1
                res = 0
                while left <= right:
                    num1, num2 = nums[left], nums[right]
                    if left == right:
                        res += num1
                    else:
                        res += concat(num1, num2)
                    left += 1
                    right -= 1
                return res
        

        4.7.274 - 2025-08-20 18:49:12 +0300 MSK

        Take Gifts From the Richest Pile

        Code

        class Solution:
            def pickGifts(self, gifts: List[int], k: int) -> int:
                for i in range(len(gifts)):
                    gifts[i] = -gifts[i]
                heapq.heapify(gifts)
                for _ in range(k):
                    val = int(math.sqrt(-heapq.heappop(gifts)))
                    heapq.heappush(gifts, -val)
                return -sum(gifts)
        

        4.7.275 - 2025-08-20 18:45:47 +0300 MSK

        Separate the Digits in an Array

        Code

        class Solution:
            def separateDigits(self, nums: List[int]) -> List[int]:
                res = []
                cur = []
                for num in nums:
                    while num > 0:
                        cur.append(num % 10)
                        num //= 10
                    cur.reverse()
                    res.extend(cur)
                    cur.clear()
                return res
        

        4.7.276 - 2025-08-20 18:44:00 +0300 MSK

        Count Distinct Numbers on Board

        Code

        class Solution:
            def distinctIntegers(self, n: int) -> int:
                if n == 1:
                    return 1
                return n - 1
        

        4.7.277 - 2025-08-20 18:28:35 +0300 MSK

        Alternating Digit Sum

        Code

        class Solution:
            def alternateDigitSum(self, n: int) -> int:
                sign = 1
                count = 0
                res = 0
                while n > 0: 
                    res += (n % 10) * sign
                    sign *= -1
                    count += 1
                    n //= 10
                if count % 2 == 0:
                    return -res
                return res
        

        4.7.278 - 2025-08-20 18:24:20 +0300 MSK

        Difference Between Element Sum and Digit Sum of an Array

        Code

        class Solution:
            def differenceOfSum(self, nums: List[int]) -> int:
                el_sum, dig_sum = 0, 0
                for num in nums:
                    el_sum += num
                    while num > 0:
                        dig_sum += num % 10
                        num //= 10
                return abs(el_sum - dig_sum)
        

        4.7.279 - 2025-08-20 18:23:07 +0300 MSK

        Maximum Count of Positive Integer and Negative Integer

        Code

        class Solution:
            def maximumCount(self, nums: List[int]) -> int:
                left, right = 0, len(nums) - 1
                start_neg, start_pos = -1, len(nums)
                while left <= right:
                    mid = left + (right - left) // 2
                    if nums[mid] >= 0:
                        right = mid - 1
                    else:
                        start_neg = mid
                        left = mid + 1
                left, right = start_neg + 1, len(nums) - 1
                while left <= right:
                    mid = left + (right - left) // 2
                    if nums[mid] > 0:
                        start_pos = mid
                        right = mid - 1
                    else:
                        left = mid + 1
                return max(start_neg + 1, len(nums) - start_pos)
        

        4.7.280 - 2025-08-20 18:22:39 +0300 MSK

        Maximum Count of Positive Integer and Negative Integer

        Code

        class Solution:
            def maximumCount(self, nums: List[int]) -> int:
                left, right = 0, len(nums) - 1
                start_neg, start_pos = -1, len(nums)
                while left <= right:
                    mid = left + (right - left) // 2
                    if nums[mid] >= 0:
                        right = mid - 1
                    else:
                        start_neg = mid
                        left = mid + 1
                left, right = start_neg + 1, len(nums) - 1
                while left <= right:
                    mid = left + (right - left) // 2
                    if nums[mid] > 0:
                        start_pos = mid
                        right = mid - 1
                    else:
                        left = mid + 1
                print(start_neg, start_pos)
                return max(start_neg + 1, len(nums) - start_pos)
        

        4.7.281 - 2025-08-20 17:57:07 +0300 MSK

        Categorize Box According to Criteria

        Code

        class Solution:
            def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str:
                is_bulky = (
                    max(length, width, height) >= 10 ** 4
                    or length * width * height >= 10 ** 9
                )
                is_heavy = mass >= 100
                if is_bulky and is_heavy:
                    return "Both"
                if is_bulky and not is_heavy:
                    return "Bulky"
                if is_heavy and not is_bulky:
                    return "Heavy"
                return "Neither"
                
        

        4.7.282 - 2025-08-20 17:48:38 +0300 MSK

        Count the Digits That Divide a Number

        Code

        class Solution:
            def countDigits(self, num: int) -> int:
                cur = num
                res = 0
                while cur > 0:
                    dig = cur % 10
                    if num % dig == 0:
                        res += 1
                    cur //= 10
                return res
        

        4.7.283 - 2025-08-20 17:47:52 +0300 MSK

        Shortest Distance to Target String in a Circular Array

        Code

        class Solution:
            def closestTarget(self, words: List[str], target: str, startIndex: int) -> int:
                n = len(words)
                for i in range(n):
                    left, right = (startIndex - i + n) % n, (startIndex + i) % n
                    if words[left] == target or words[right] == target:
                        return i
                return -1
        

        4.7.284 - 2025-08-20 17:43:24 +0300 MSK

        Maximum Enemy Forts That Can Be Captured

        Code

        class Solution:
            def captureForts(self, forts: List[int]) -> int:
                start = None
                max_capt = 0
                for i, fort in enumerate(forts):
                    if fort == 0:
                        continue
                    if start is None:
                        start = i
                        continue
                    start_val = forts[start]
                    if (start_val == 1 and fort == -1) or (start_val == -1 and fort == 1):
                        max_capt = max(max_capt, i - start - 1)
                    start = i
                return max_capt
        

        4.7.285 - 2025-08-20 17:23:29 +0300 MSK

        Count Pairs Of Similar Strings

        Code

        class Solution:
            def similarPairs(self, words: List[str]) -> int:
                freqs = defaultdict(int)
                res = 0
                for word in words:
                    freq = 0
                    for char in word:
                        freq |= 1 << (ord(char) - 97)
                    res += freqs[freq]
                    freqs[freq] += 1
                return res
        

        4.7.286 - 2025-08-20 17:18:47 +0300 MSK

        Count Pairs Of Similar Strings

        Code

        class Solution:
            def similarPairs(self, words: List[str]) -> int:
                freqs = [False] * 26
                freqs2 = defaultdict(int)
                for word in words:
                    for char in word:
                        freqs[ord(char) - 97] = True
                    freqs2[tuple(freqs)] += 1
                    for i in range(26):
                        freqs[i] = False
                res = 0
                for freq in freqs2.values():
                    for i in range(freq):
                        res += (freq - i - 1)
                return res
        

        4.7.287 - 2025-08-20 15:09:02 +0300 MSK

        Delete Greatest Value in Each Row

        Code

        class Solution:
            def deleteGreatestValue(self, grid: List[List[int]]) -> int:
                for row in grid:
                    row.sort()
                res = 0
                for _ in range(len(grid[0])):
                    cur_sum = 0
                    for row in grid:
                        cur_sum = max(cur_sum, row.pop())
                    res += cur_sum
                return res
        

        4.7.288 - 2025-08-20 13:48:16 +0300 MSK

        Maximum Value of a String in an Array

        Code

        class Solution:
            def maximumValue(self, strs: List[str]) -> int:
                max_val = 0
                for s in strs:
                    if s.isdigit():
                        val = int(s)
                    else:
                        val = len(s)
                    if val > max_val:
                        max_val = val
                return max_val
        

        4.7.289 - 2025-08-20 13:45:38 +0300 MSK

        Circular Sentence

        Code

        class Solution:
            def isCircularSentence(self, sentence: str) -> bool:
                if sentence[0] != sentence[-1]:
                    return False
                for i, char in enumerate(sentence):
                    if char == " " and sentence[i - 1] != sentence[i + 1]:
                        return False
                return True
                    
        

        4.7.290 - 2025-08-20 13:41:05 +0300 MSK

        Minimum Cuts to Divide a Circle

        Code

        class Solution:
            def numberOfCuts(self, n: int) -> int:
                if n == 1:
                    return 0
                if n % 2 == 0:
                    return n // 2
                return n
        

        4.7.291 - 2025-08-20 13:36:58 +0300 MSK

        Number of Unequal Triplets in Array

        Code

        class Solution:
            def unequalTriplets(self, nums: List[int]) -> int:
                freqs = [0] * 1001
                for num in nums:
                    freqs[num] += 1
                res = 0
                left = 0
                right = len(nums)
                for freq in freqs:
                    if freq == 0:
                        continue
                    right -= freq
                    res += left * freq * right
                    left += freq
                return res
        

        4.7.292 - 2025-08-20 13:29:30 +0300 MSK

        Number of Unequal Triplets in Array

        Code

        class Solution:
            def unequalTriplets(self, nums: List[int]) -> int:
                freqs = [0] * 1001
                for num in nums:
                    freqs[num] += 1
                res = 0
                left = 0
                right = len(nums)
                for freq in freqs:
                    if freq == 0:
                        continue
                    right -= freq
                    res += left * freq * right
                    left += freq
                return res
        

        4.7.293 - 2025-08-20 13:16:55 +0300 MSK

        Convert the Temperature

        Code

        class Solution:
            def convertTemperature(self, celsius: float) -> List[float]:
                return (celsius + 273.15, (celsius * 1.80 + 32.00))
        

        4.7.294 - 2025-08-20 13:13:48 +0300 MSK

        Number of Distinct Averages

        Code

        class Solution:
            def distinctAverages(self, nums: List[int]) -> int:
                nums.sort()
                freqs = [False] * 201
                n = len(nums)
                res = 0
                for i in range(n // 2 + 1):
                    freq = nums[i] + nums[n - i - 1]
                    if not freqs[freq]:
                        res += 1
                        freqs[freq] = True
                return res
        

        4.7.295 - 2025-08-20 13:06:17 +0300 MSK

        Apply Operations to an Array

        Code

        class Solution:
            def applyOperations(self, nums: List[int]) -> List[int]:
                n = len(nums)
                for i in range(1, n):
                    cur, prev = nums[i], nums[i - 1]
                    if prev != 0 and cur == prev:
                        nums[i], nums[i - 1] = 0, prev * 2
                left, right = 0, 1
                while left < n and right < n:
                    num1, num2 = nums[left], nums[right]
                    if num1 != 0:
                        left += 1
                    elif num2 == 0:
                        right += 1
                    elif left >= right:
                        right += 1
                    else:
                        nums[left], nums[right] = num2, 0
                        left += 1
                        right += 1
                return nums
        

        4.7.296 - 2025-08-20 12:43:09 +0300 MSK

        Average Value of Even Numbers That Are Divisible by Three

        Code

        class Solution:
            def averageValue(self, nums: List[int]) -> int:
                res = 0
                cnt = 0
                for num in nums:
                    if num % 2 == 0 and num % 3 == 0:
                        cnt += 1
                        res += num
                if cnt == 0:
                    return 0
                return res // cnt
        

        4.7.297 - 2025-08-20 12:38:03 +0300 MSK

        Odd String Difference

        Code

        class Solution:
            def oddString(self, words: List[str]) -> str:
                freq1, freq2, cur = None, None, []
                freq1_word, freq2_word = None, None
                freq1_cnt, freq2_cnt = 0, 0
                for word in words:
                    for i in range(1, len(word)):
                        cur.append(ord(word[i]) - ord(word[i - 1]))
                    if freq1 is None:
                        freq1, freq1_word, freq1_cnt = cur, word, 1
                        cur = []
                    elif cur == freq1:
                        freq1_cnt += 1
                    elif freq2 is None:
                        freq2, freq2_word, freq2_cnt = cur, word, 1
                        cur = []
                    elif cur == freq2:
                        freq2_cnt += 1
                    cur.clear()
                    if min(freq1_cnt, freq2_cnt) == 1 and max(freq1_cnt, freq2_cnt) > 1:
                        if freq1_cnt == 1:
                            return freq1_word
                        return freq2_word
                raise Exception
        

        4.7.298 - 2025-08-20 12:08:13 +0300 MSK

        Count Square Submatrices with All Ones

        Code

        class Solution:
            def countSquares(self, matrix: List[List[int]]) -> int:
                rows, cols = len(matrix), len(matrix[0])
                dp = [[0] * (cols + 1) for _ in range(rows + 1)]
                res = 0
                for row in range(rows):
                    for col in range(cols):
                        val = matrix[row][col]
                        if val == 0:
                            continue
                        dp_row, dp_col = row + 1, col + 1
                        dp_val = min(
                            dp[dp_row - 1][dp_col], 
                            dp[dp_row][dp_col - 1], 
                            dp[dp_row - 1][dp_col - 1]
                        ) + 1
                        dp[dp_row][dp_col] = dp_val
                        res += dp_val
                return res
        

        4.7.299 - 2025-08-19 20:23:46 +0300 MSK

        Determine if Two Events Have Conflict

        Code

        class Solution:
            def haveConflict(self, event1: List[str], event2: List[str]) -> bool:
                def parse(clock: str) -> int:
                    hh, mm = clock[:2], clock[2:]
                    return hh * 60 + mm
                start1, end1 = map(parse, event1)
                start2, end2 = map(parse, event2)
                if start1 == start2:
                    return True
                if start1 > start2:
                    return start1 <= end2
                return end1 >= start2
        

        4.7.300 - 2025-08-19 20:13:25 +0300 MSK

        Number of Valid Clock Times

        Code

        class Solution:
            def countTime(self, time: str) -> int:
                hh, mm = time.split(':')
                count_possible_hours = 1
                if (hh == '??'):
                    count_possible_hours = 24
                elif (hh[0] == '?' and int(hh[1]) >= 4):
                    count_possible_hours = 2
                elif (hh[0] == '?' and int(hh[1]) <= 4):
                    count_possible_hours = 3
                elif (int(hh[0]) <= 1 and hh[1] == '?'):
                    count_possible_hours = 10
                elif (int(hh[0]) == 2 and hh[1] == '?'):
                    count_possible_hours = 4
                count_possible_minutes = 1
                if (mm == '??'):
                    count_possible_minutes = 60
                elif (mm[0] == '?'):
                    count_possible_minutes = 6
                elif (mm[1] == '?'):
                    count_possible_minutes = 10
                return count_possible_hours * count_possible_minutes
        

        4.7.301 - 2025-08-19 20:11:33 +0300 MSK

        The Employee That Worked on the Longest Task

        Code

        class Solution:
            def hardestWorker(self, n: int, logs: List[List[int]]) -> int:
                max_id, max_dur = logs[0]
                for i, (emp_id, leave) in enumerate(logs[1:], 1):
                    dur = leave - logs[i - 1][1]
                    if dur > max_dur:
                        max_id, max_dur = emp_id, dur
                    elif dur == max_dur and emp_id < max_id:
                        max_id = emp_id
                return max_id
        

        4.7.302 - 2025-08-19 20:00:15 +0300 MSK

        Number of Common Factors

        Code

        class Solution:
            def commonFactors(self, a: int, b: int) -> int:
                res = 0
                for i in range(1, min(a, b) + 1):
                    if a % i == 0 and b % i == 0:
                        res += 1
                return res
                
        

        4.7.303 - 2025-08-19 19:47:47 +0300 MSK

        Remove Letter To Equalize Frequency

        Code

        class Solution:
            def equalFrequency(self, word: str) -> bool:
                freqs1, freqs2 = defaultdict(int), defaultdict(int)
                for char in word:
                    freqs1[char] += 1
                for freq in freqs1.values():
                    freqs2[freq] += 1
                if len(freqs2) == 1:
                    return next(iter(freqs2.keys())) == 1 or next(iter(freqs2.values())) == 1
                if len(freqs2) == 2:
                    f1, f2 = min(freqs2.keys()), max(freqs2.keys())
                    return (
                        f1 + 1 == f2 and freqs2[f2] == 1
                    ) or (
                        f1 == 1 and freqs2[f1] == 1
                    )
                return False
        

        4.7.304 - 2025-08-19 16:10:29 +0300 MSK

        Sort the People

        Code

        class Solution:
            def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
                for i in range(len(names)):
                    names[i] = (heights[i], names[i])
                names.sort(reverse=True)
                for i in range(len(names)):
                    names[i] = names[i][1]
                return names
        

        4.7.305 - 2025-08-19 15:27:24 +0300 MSK

        Smallest Even Multiple

        Code

        class Solution:
            def smallestEvenMultiple(self, n: int) -> int:
                if n % 2 == 0:
                    return n
                return n * 2
        

        4.7.306 - 2025-08-19 15:24:40 +0300 MSK

        Count Days Spent Together

        Code

        class Solution:
            def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
                months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
                def count(date: str) -> int:
                    month = int(date[:2])
                    days = int(date[3:])
                    return sum(months[:month - 1]) + days
                return max(0, count(min(leaveAlice, leaveBob)) - count(max(arriveAlice, arriveBob)) + 1)
            
        

        4.7.307 - 2025-08-19 15:04:21 +0300 MSK

        Most Frequent Even Element

        Code

        class Solution:
            def mostFrequentEven(self, nums: List[int]) -> int:
                nums.sort()
                max_freq, max_freq_num = 0, -1
                cur_freq = 0
                prev = -1
                for num in nums:
                    if num % 2 != 0:
                        continue
                    if num == prev:
                        cur_freq += 1
                    else:
                        cur_freq, prev = 1, num
                    if cur_freq > max_freq:
                        max_freq, max_freq_num = cur_freq, num
                return max_freq_num
        

        4.7.308 - 2025-08-19 14:58:59 +0300 MSK

        Check Distances Between Same Letters

        Code

        class Solution:
            def checkDistances(self, s: str, distance: List[int]) -> bool:
                for i, char in enumerate(s):
                    idx = ord(char) - 97
                    dist = distance[idx]
                    if dist == -1:
                        continue
                    nxt = i + dist + 1
                    if nxt >= len(s) or s[nxt] != char:
                        return False
                    distance[idx] = -1
                return True
        

        4.7.309 - 2025-08-19 14:42:34 +0300 MSK

        Find Subarrays With Equal Sum

        Code

        class Solution:
            def findSubarrays(self, nums: List[int]) -> bool:
                enc = set()
                for i in range(1, len(nums)):
                    val = nums[i] + nums[i - 1]
                    if val in enc:
                        return True
                    enc.add(val)
                return False
        

        4.7.310 - 2025-08-19 14:37:35 +0300 MSK

        Longest Subsequence With Limited Sum

        Code

        class Solution:
            def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
                nums.sort()
                for i in range(1, len(nums)):
                    nums[i] += nums[i - 1]
                for i in range(len(queries)):
                    target = queries[i]
                    count = 0
                    for num in nums:
                        if num <= target:
                            count += 1
                        else:
                            break
                    queries[i] = count
                return queries
        

        4.7.311 - 2025-08-19 14:29:00 +0300 MSK

        Minimum Hours of Training to Win a Competition

        Code

        class Solution:
            def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
                res = max(0, sum(energy) - initialEnergy + 1)
                for exp in experience:
                    if initialExperience <= exp:
                        diff = exp - initialExperience + 1
                        res += diff
                        initialExperience += diff
                    initialExperience += exp
                return res
        

        4.7.312 - 2025-08-19 14:04:31 +0300 MSK

        Minimum Recolors to Get K Consecutive Black Blocks

        Code

        class Solution:
            def minimumRecolors(self, blocks: str, k: int) -> int:
                left = 0
                num_whites = 0
                num_recolors = math.inf
                for right in range(len(blocks)):
                    if blocks[right] == "W":
                        num_whites += 1
                    if right - left + 1 == k:
                        num_recolors = min(num_recolors, num_whites)
                        if blocks[left] == "W":
                            num_whites -= 1
                        left += 1
                return num_recolors
        

        4.7.313 - 2025-08-19 13:54:21 +0300 MSK

        Number of Arithmetic Triplets

        Code

        class Solution:
            def arithmeticTriplets(self, nums: List[int], diff: int) -> int:
                freqs = [[] for _ in range(201)]
                for i, num in enumerate(nums):
                    freqs[num].append(i)
                length = len(nums)
                res = 0
                for i in range(length):
                    num1 = nums[i]
                    for j in range(i + 1, length):
                        num2 = nums[j]
                        if num2 - num1 != diff:
                            continue
                        num3 = num2 + diff 
                        if num3 > 200:
                            continue
                        for k in freqs[num3]:
                            if k > j:
                                res += 1
                                break
                return res
        

        4.7.314 - 2025-08-19 13:40:19 +0300 MSK

        Merge Similar Items

        Code

        class Solution:
            def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
                freqs = [0] * 1001
                for val, weight in itertools.chain(items1, items2):
                    freqs[val] += weight
                res = [(num, weight) for num, weight in enumerate(freqs) if weight != 0]
                return res
        

        4.7.315 - 2025-08-19 13:37:47 +0300 MSK

        Merge Similar Items

        Code

        class Solution:
            def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
                freqs = [(i, 0) for i in range(1001)]
                for val, weight in itertools.chain(items1, items2):
                    _, cur_weight = freqs[val]
                    freqs[val] = (val, weight + cur_weight)
                freqs.sort(reverse=True, key=lambda val: val[1])
                while freqs and freqs[-1][1] == 0:
                    freqs.pop()
                freqs.sort()
                return freqs
        

        4.7.316 - 2025-08-19 13:11:40 +0300 MSK

        Make Array Zero by Subtracting Equal Amounts

        Code

        class Solution:
            def minimumOperations(self, nums: List[int]) -> int:
                nums.sort(reverse=True)
                res = 0
                while nums:
                    num = nums.pop()
                    if num == 0:
                        continue
                    for i in range(len(nums)):
                        nums[i] = max(0, nums[i] - num)
                    res += 1
                return res
        

        4.7.317 - 2025-08-19 11:34:12 +0300 MSK

        Number of Unique Subjects Taught by Each Teacher

        Code

        SELECT
            teacher_id,
            COUNT(DISTINCT subject_id) AS "cnt"
        FROM
            Teacher
        GROUP BY
            teacher_id
        

        4.7.318 - 2025-08-19 09:58:54 +0300 MSK

        First Letter to Appear Twice

        Code

        class Solution:
            def repeatedCharacter(self, s: str) -> str:
                freqs = [0] * 26
                for char in s:
                    idx = ord(char) - 97
                    freq = freqs[idx] + 1
                    if freq == 2:
                        return char
                    freqs[idx] = freq
                raise Exception
        

        4.7.319 - 2025-08-19 08:52:54 +0300 MSK

        Best Poker Hand

        Code

        class Solution:
            def bestHand(self, ranks: List[int], suits: List[str]) -> str:
                ranks.sort()
                suits.sort()
                same_suit = 1
                cur_same_suit = 1
                same_rank = 1
                cur_same_rank = 1
                for i in range(1, len(ranks)):
                    if ranks[i] == ranks[i - 1]:
                        cur_same_rank += 1
                        same_rank = max(same_rank, cur_same_rank)
                    else:
                        cur_same_rank = 1
                    if suits[i] == suits[i - 1]:
                        cur_same_suit += 1
                        same_suit = max(same_suit, cur_same_suit)
                    else:
                        cur_same_suit = 1
                print(same_suit, same_rank)
                if same_suit == 5:
                    return "Flush"
                if same_rank >= 3:
                    return "Three of a Kind"
                if same_rank >= 2:
                    return "Pair"
                return "High Card"
        

        4.7.320 - 2025-08-19 08:18:09 +0300 MSK

        Number of Zero-Filled Subarrays

        Code

        class Solution:
            def zeroFilledSubarray(self, nums: List[int]) -> int:
                res = 0
                cur = 0
                for num in nums:
                    if num == 0:
                        cur += 1
                        res += cur
                    elif cur != 0:
                        cur = 0
                return res
        

        4.7.321 - 2025-08-18 21:10:17 +0300 MSK

        Maximum Number of Pairs in Array

        Code

        class Solution:
            def numberOfPairs(self, nums: List[int]) -> List[int]:
                cnt_pair, cnt_rest = 0, 0
                nums.sort()
                length = len(nums)
                i = 0
                while i < length:
                    cur = nums[i]
                    nxt = nums[i + 1] if i + 1 < length else -1
                    if nxt == cur:
                        cnt_pair += 1
                        i += 2
                    else:
                        cnt_rest += 1
                        i += 1
                return cnt_pair, cnt_rest
        

        4.7.322 - 2025-08-18 21:06:45 +0300 MSK

        Minimum Amount of Time to Fill Cups

        Code

        class Solution:
            def fillCups(self, amount: List[int]) -> int:
                res = 0
                for i in range(len(amount)):
                    amount[i] = -amount[i]
                heapq.heapify(amount)
                while len(amount) > 2:
                    num1, num2 = heapq.heappop(amount), heapq.heappop(amount)
                    if num1 < 0 or num2 < 0:
                        res += 1
                    if num1 < 0:
                        num1 += 1
                        heapq.heappush(amount, num1)
                    if num2 < 0:
                        num2 += 1
                        heapq.heappush(amount, num2)
                if len(amount) == 1:
                    return res - amount[0]
                num1, num2 = amount
                res += min(-num1, -num2) + abs(num1 - num2)
                return res
        

        4.7.323 - 2025-08-18 20:23:18 +0300 MSK

        Decode the Message

        Code

        class Solution:
            def decodeMessage(self, key: str, message: str) -> str:
                subst = [-1] * 26
                res = []
                count = 0
                for char in key:
                    if char == " ":
                        continue
                    idx = ord(char) - 97
                    if subst[idx] == -1:
                        subst[idx] = count
                        count += 1
                for char in message:
                    if char == " ":
                        val = char
                    else:
                        val = chr(subst[ord(char) - 97] + 97)
                    res.append(val)
                return "".join(res)
        

        4.7.324 - 2025-08-18 20:18:16 +0300 MSK

        Check if Matrix Is X-Matrix

        Code

        class Solution:
            def checkXMatrix(self, grid: List[List[int]]) -> bool:
                length = len(grid)
                for row in range(length):
                    for col in range(length):
                        is_diag = row == col or length - row - 1 == col
                        val = grid[row][col]
                        if (is_diag and val == 0) or (not is_diag and val != 0):
                            return False
                return True
        

        4.7.325 - 2025-08-18 20:07:07 +0300 MSK

        Count Asterisks

        Code

        class Solution:
            def countAsterisks(self, s: str) -> int:
                start = False
                res = 0
                for char in s:
                    if char == "|":
                        start = not start
                    elif char == "*" and not start:
                        res += 1
                return res
        

        4.7.326 - 2025-08-18 20:04:04 +0300 MSK

        Greatest English Letter in Upper and Lower Case

        Code

        class Solution:
            def greatestLetter(self, s: str) -> str:
                freqs = [(False, False)] * 26
                for char in reversed(s):
                    if char.islower():
                        idx = ord(char) - 97
                        is_lower = True
                    else:
                        idx = ord(char) - 65
                        is_lower = False
                    enc_lower, enc_upper = freqs[idx]
                    new_val = (enc_lower or is_lower, enc_upper or not is_lower)
                    if new_val != (enc_lower, enc_upper):
                        freqs[idx] = new_val
                for i in reversed(range(len(freqs))):
                    if all(freqs[i]):
                        return chr(i + 65)
                return ""
        

        4.7.327 - 2025-08-18 19:52:53 +0300 MSK

        Calculate Amount Paid in Taxes

        Code

        class Solution:
            def calculateTax(self, brackets: List[List[int]], income: int) -> float:
                tax = prev = 0
                for upper, perc in brackets:
                    if income >= upper:
                        tax += (upper - prev) * perc / 100
                        prev = upper
                    else:
                        tax += (income - prev) * perc / 100
                        return tax
                return tax
        

        4.7.328 - 2025-08-18 19:41:27 +0300 MSK

        Strong Password Checker II

        Code

        class Solution:
            def strongPasswordCheckerII(self, password: str) -> bool:
                if len(password) < 8:
                    return False
                has_lower, has_upper, has_digit, has_spec = False, False, False, False
                prev = None
                spec = "!@#$%^&*()-+"
                for char in password:
                    if char.islower():
                        has_lower = True
                    elif char.isupper():
                        has_upper = True
                    elif char.isdigit():
                        has_digit = True
                    elif char in spec:
                        has_spec = True
                    if prev is not None and char == prev:
                        return False
                    prev = char
                return has_lower and has_upper and has_digit and has_spec
        

        4.7.329 - 2025-08-18 19:36:10 +0300 MSK

        Min Max Game

        Code

        class Solution:
            def minMaxGame(self, nums: List[int]) -> int:
                while len(nums) > 1:
                    length = len(nums) // 2
                    for i in range(length):
                        if i % 2 == 0:
                            nums[i] = min(nums[i * 2], nums[i * 2 + 1])
                        else:
                            nums[i] = max(nums[i * 2], nums[i * 2 + 1])
                    while len(nums) > length:
                        nums.pop()
                return nums[0]
        

        4.7.330 - 2025-08-18 19:26:10 +0300 MSK

        Rearrange Characters to Make Target String

        Code

        class Solution:
            def rearrangeCharacters(self, s: str, target: str) -> int:
                freqs1, freqs2 = [0] * 26, [0] * 26
                for char in s:
                    freqs1[ord(char) - 97] += 1
                for char in target:
                    freqs2[ord(char) - 97] += 1
                count = math.inf
                for i in range(26):
                    freq1, freq2 = freqs1[i], freqs2[i]
                    if freq2 == 0:
                        continue
                    cur_count = freq1 // freq2
                    if cur_count == 0:
                        return 0
                    if cur_count < count:
                        count = cur_count
                return count
        

        4.7.331 - 2025-08-18 19:21:41 +0300 MSK

        Check if Number Has Equal Digit Count and Digit Value

        Code

        class Solution:
            def digitCount(self, num: str) -> bool:
                freqs = [0] * 10
                for char in num:
                    freqs[int(char)] += 1
                for i, char in enumerate(num):
                    if freqs[i] != int(char):
                        return False
                return True
        

        4.7.332 - 2025-08-18 19:16:20 +0300 MSK

        Percentage of Letter in String

        Code

        class Solution:
            def percentageLetter(self, s: str, letter: str) -> int:
                count = 0
                for char in s:
                    if char == letter:
                        count += 1
                return (count * 100) // len(s)
        

        4.7.333 - 2025-08-18 19:11:33 +0300 MSK

        Find Resultant Array After Removing Anagrams

        Code

        class Solution:
            def removeAnagrams(self, words: List[str]) -> List[str]:
                freqs1, freqs2 = bytearray(26), bytearray(26)
                res = []
                for i, word in enumerate(words):
                    for i in range(26):
                        freqs2[i] = 0
                    for char in word:
                        freqs2[ord(char) - 97] += 1
                    if i != 0 and freqs1 == freqs2:
                        continue
                    freqs1, freqs2 = freqs2, freqs1
                    res.append(word)
                return res
        

        4.7.334 - 2025-08-18 19:02:01 +0300 MSK

        Find Resultant Array After Removing Anagrams

        Code

        class Solution:
            def removeAnagrams(self, words: List[str]) -> List[str]:
                prev = ()
                res = []
                for word in words:
                    word_sorted = sorted(word)
                    if prev != word_sorted:
                        res.append(word)
                        prev = word_sorted
                return res
        

        4.7.335 - 2025-08-18 18:43:22 +0300 MSK

        Find the K-Beauty of a Number

        Code

        class Solution:
            def divisorSubstrings(self, num: int, k: int) -> int:
                digits = []
                cur_num = num
                while cur_num > 0:
                    digits.append(cur_num % 10)
                    cur_num //= 10
                digits.reverse()
                length = len(digits)
                if length < k:
                    return 0
                cur_sum = 0
                res = 0
                for i in range(k):
                    cur_sum += digits[i] * (10 ** (k - i - 1))
                if num % cur_sum == 0:
                    res += 1 
                i = k
                while i < length:
                    cur_sum -= digits[i - k] * (10 ** (k - 1))
                    cur_sum = cur_sum * 10 + digits[i]
                    if cur_sum != 0 and num % cur_sum == 0:
                        res += 1
                    i += 1
                return res
        

        4.7.336 - 2025-08-18 15:12:00 +0300 MSK

        Remove Digit From Number to Maximize Result

        Code

        class Solution:
            def removeDigit(self, number: str, digit: str) -> str:
                last_index = 0
                digit_int = int(digit)
                for i in range(1, len(number)):
                    cur, prev = int(number[i]), int(number[i - 1])
                    if prev == digit_int:
                        if cur > prev:
                            return "".join((number[:i-1], number[i:]))
                        else:
                            last_index = i - 1
                if number[-1] == digit:
                    last_index = len(number) - 1
                return "".join((number[:last_index], number[last_index + 1:]))
        

        4.7.337 - 2025-08-18 15:03:06 +0300 MSK

        Count Prefixes of a Given String

        Code

        class Solution:
            def countPrefixes(self, words: List[str], s: str) -> int:
                res = 0
                for word in words:
                    if s.startswith(word):
                        res += 1
                return res
        

        4.7.338 - 2025-08-18 14:55:52 +0300 MSK

        Intersection of Multiple Arrays

        Code

        class Solution:
            def intersection(self, nums: List[List[int]]) -> List[int]:
                length = len(nums)
                freqs = [[False] * length for _ in range(1002)] 
                for i, arr in enumerate(nums):
                    for num in arr:
                        if not freqs[num][i]:
                            freqs[num][i] = True
                nums.clear()
                for num, freq in enumerate(freqs):
                    if all(freq):
                        nums.append(num)
                return nums
        

        4.7.339 - 2025-08-18 14:48:14 +0300 MSK

        Intersection of Multiple Arrays

        Code

        class Solution:
            def intersection(self, nums: List[List[int]]) -> List[int]:
                enc = set(nums[0])
                for arr in nums[1:]:
                    enc.intersection_update(arr)
                return sorted(enc)
        

        4.7.340 - 2025-08-18 14:43:36 +0300 MSK

        Calculate Digit Sum of a String

        Code

        class Solution:
            def digitSum(self, s: str, k: int) -> str:
                res, cur, group = list(map(int, s)), [], []
                i = 0
                def add_digits(num: int) -> None:
                    if num == 0:
                        cur.append(0)
                        return
                    while num > 0:
                        group.append(num % 10)
                        num //= 10
                    group.reverse()
                    cur.extend(group)
                    group.clear()
                while len(res) > k:
                    while i < len(res):
                        add_digits(sum(res[i:i + k]))
                        i += k
                    res, cur = cur, res
                    cur.clear()
                    i = 0
                return "".join(map(str, res))
        

        4.7.341 - 2025-08-18 13:44:46 +0300 MSK

        Find Closest Number to Zero

        Code

        class Solution:
            def findClosestNumber(self, nums: List[int]) -> int:
                max_diff, max_num = math.inf, 0
                for num in nums:
                    diff = abs(num)
                    if diff < max_diff or (diff == max_diff and num > max_num):
                        max_diff, max_num = diff, num
                return max_num
        

        4.7.342 - 2025-08-18 13:40:40 +0300 MSK

        Largest Number After Digit Swaps by Parity

        Code

        class Solution:
            def largestInteger(self, num: int) -> int:
                odd, even, digits = [], [], []
                while num > 0:
                    dig = num % 10
                    if dig % 2 == 0:
                        heapq.heappush(even, dig)
                        digits.append(True)
                    else:
                        heapq.heappush(odd, dig)
                        digits.append(False)
                    num //= 10
                res = 0
                for i in range(len(digits)):
                    if digits[i]:
                        target = even
                    else:
                        target = odd
                    res += heapq.heappop(target) * (10 ** i)
                return res
                
        

        4.7.343 - 2025-08-18 13:34:09 +0300 MSK

        Largest Number After Digit Swaps by Parity

        Code

        class Solution:
            def largestInteger(self, num: int) -> int:
                odd, even, res = [], [], []
                while num > 0:
                    dig = num % 10
                    if dig % 2 == 0:
                        even.append(dig)
                        res.append(True)
                    else:
                        odd.append(dig)
                        res.append(False)
                    num //= 10
                odd.sort(reverse=True)
                even.sort(reverse=True)
                res.reverse()
                length = len(res)
                num = 0
                for i in reversed(range(length)):
                    if res[i]:
                        num += even.pop() * (10 ** (length - i - 1))
                    else:
                        num += odd.pop() * (10 ** (length - i - 1))
                return num
                
        

        4.7.344 - 2025-08-18 10:06:49 +0300 MSK

        24 Game

        Code

        from typing import List
        import math
        
        class Solution:
            def judgePoint24(self, cards: List[int]) -> bool:
                EPS = 1e-6
        
                def backtrack(nums: List[float]) -> bool:
                    if len(nums) == 1:
                        return abs(nums[0] - 24.0) < EPS
        
                    n = len(nums)
                    for i in range(n):
                        for j in range(i + 1, n):
                            rest = [nums[k] for k in range(n) if k != i and k != j]
                            a, b = nums[i], nums[j]
        
                            candidates = []
                            candidates.append(a + b)
                            candidates.append(a * b)
                            candidates.append(a - b)
                            candidates.append(b - a)
        
                            if abs(b) > EPS:
                                candidates.append(a / b)
                            if abs(a) > EPS:
                                candidates.append(b / a)
        
                            for x in candidates:
                                if backtrack(rest + [x]):
                                    return True
                    return False
        
                return backtrack([float(x) for x in cards])
        

        4.7.345 - 2025-08-17 20:02:56 +0300 MSK

        Minimum Number of Operations to Convert Time

        Code

        class Solution:
            def convertTime(self, current: str, correct: str) -> int:
                current_time = 60 * int(current[0:2]) + int(current[3:5])
                target_time = 60 * int(correct[0:2]) + int(correct[3:5])
                diff = target_time - current_time
                count = 0
                for i in (60, 15, 5, 1):
                    count += diff // i
                    diff %= i
                return count
        

        4.7.346 - 2025-08-17 19:56:52 +0300 MSK

        Divide Array Into Equal Pairs

        Code

        class Solution:
            def divideArray(self, nums: List[int]) -> bool:
                nums.sort()
                prev = nums[0]
                count = 1
                for num in nums[1:]:
                    if num == prev:
                        count += 1
                    elif count % 2 != 0:
                        return False
                    else:
                        count = 1
                        prev = num
                return count % 2 == 0
        

        4.7.347 - 2025-08-17 19:54:48 +0300 MSK

        Divide Array Into Equal Pairs

        Code

        class Solution:
            def divideArray(self, nums: List[int]) -> bool:
                freqs = defaultdict(int)
                for num in nums:
                    freqs[num] += 1
                for freq in freqs.values():
                    if freq % 2 != 0:
                        return False
                return True
        

        4.7.348 - 2025-08-17 19:44:55 +0300 MSK

        Find All K-Distant Indices in an Array

        Code

        class Solution:
            def findKDistantIndices(
                self, nums: List[int], key: int, k: int
            ) -> List[int]:
                res = []
                right = 0 
                length = len(nums)
                for j in range(length):
                    if nums[j] != key:
                        continue
                    left = max(right, j - k)
                    right = min(length - 1, j + k) + 1
                    res.extend(range(left, right))
                return res
        

        4.7.349 - 2025-08-17 19:21:20 +0300 MSK

        Cells in a Range on an Excel Sheet

        Code

        class Solution:
            def cellsInRange(self, s: str) -> List[str]:
                cell1, cell2 = s.split(":")
                row1, col1 = cell1[0], int(cell1[1:])
                row2, col2 = cell2[0], int(cell2[1:])
                res = []
                while row1 <= row2:
                    for col in range(col1, col2 + 1):
                        res.append(f"{row1}{col}")
                    row1 = chr(ord(row1) + 1)
                return res
        

        4.7.350 - 2025-08-17 19:15:00 +0300 MSK

        Most Frequent Number Following Key In an Array

        Code

        class Solution:
            def mostFrequent(self, nums: List[int], key: int) -> int:
                freqs = [0] * 1001
                prev = nums[0]
                max_freq, max_freq_num = 0, 0
                res = 0
                for num in nums[1:]:
                    if prev == key:
                        freq = freqs[num] + 1 
                        freqs[num] = freq
                        if freq > max_freq:
                            max_freq, max_freq_num = freq, num
                    prev = num
                return max_freq_num
        

        4.7.351 - 2025-08-17 19:10:32 +0300 MSK

        Counting Words With a Given Prefix

        Code

        class Solution:
            def prefixCount(self, words: List[str], pref: str) -> int:
                res = 0
                for word in words:
                    if word.startswith(pref):
                        res += 1
                return res
        

        4.7.352 - 2025-08-17 19:08:02 +0300 MSK

        Count Integers With Even Digit Sum

        Code

        class Solution:
            def countEven(self, num: int) -> int:
                dig_sum = 0
                val = num
                while val > 0:
                    dig_sum += val % 10
                    val //= 10
                if dig_sum % 2 == 0:
                    return num // 2
                return (num - 1) // 2
        

        4.7.353 - 2025-08-17 18:51:40 +0300 MSK

        Count Equal and Divisible Pairs in an Array

        Code

        class Solution:
            def countPairs(self, nums: List[int], k: int) -> int:
                freqs = tuple([] for i in range(101))
                res = 0
                for j, num in enumerate(nums):
                    for i in freqs[num]:
                        if (i * j) % k == 0:
                            res += 1
                    freqs[num].append(j)
                return res
        

        4.7.354 - 2025-08-17 18:46:10 +0300 MSK

        Count Equal and Divisible Pairs in an Array

        Code

        class Solution:
            def countPairs(self, nums: List[int], k: int) -> int:
                length = len(nums)
                res = 0
                for i in range(length):
                    num1 = nums[i]
                    for j in range(i + 1, length):
                        if (i * j) % k == 0 and num1 == nums[j]:
                            res += 1
                return res
        

        4.7.355 - 2025-08-17 18:44:14 +0300 MSK

        Count Equal and Divisible Pairs in an Array

        Code

        class Solution:
            def countPairs(self, nums: List[int], k: int) -> int:
                length = len(nums)
                res = 0
                for i in range(length):
                    num1 = nums[i]
                    for j in range(i + 1, length):
                        if num1 == nums[j] and (i * j) % k == 0:
                            res += 1
                return res
        

        4.7.356 - 2025-08-17 18:40:15 +0300 MSK

        Count Operations to Obtain Zero

        Code

        class Solution:
            def countOperations(self, num1: int, num2: int) -> int:
                count = 0
                while num1 > 0 and num2 > 0:
                    if num1 >= num2:
                        count += num1 // num2
                        num1 %= num2
                    else:
                        count += num2 // num1
                        num2 %= num1
                return count
        

        4.7.357 - 2025-08-17 18:38:02 +0300 MSK

        Count Operations to Obtain Zero

        Code

        class Solution:
            def countOperations(self, num1: int, num2: int) -> int:
                count = 0
                while num1 > 0 and num2 > 0:
                    if num1 >= num2:
                        num1 -= num2
                    else:
                        num2 -= num1
                    count += 1
                return count
        

        4.7.358 - 2025-08-17 18:25:12 +0300 MSK

        Sort Even and Odd Indices Independently

        Code

        class Solution:
            def sortEvenOdd(self, nums: List[int]) -> List[int]:
                odd, even = [], []
                for i, num in enumerate(nums):
                    if i % 2 == 0:
                        heapq.heappush(even, num)
                    else:
                        heapq.heappush(odd, -num)
                for i in range(len(nums)):
                    if i % 2 == 0:
                        nums[i] = heapq.heappop(even)
                    else:
                        nums[i] = -heapq.heappop(odd)
                return nums
        

        4.7.359 - 2025-08-17 18:16:02 +0300 MSK

        Minimum Sum of Four Digit Number After Splitting Digits

        Code

        class Solution:
            def minimumSum(self, num: int) -> int:
                digits = []
                while num > 0:
                    digits.append(num % 10)
                    num //= 10
                digits.sort()
                return digits[0] * 10 + digits[1] * 10 + digits[2] + digits[3]
        

        4.7.360 - 2025-08-17 18:06:00 +0300 MSK

        Keep Multiplying Found Values by Two

        Code

        class Solution:
            def findFinalValue(self, nums: List[int], original: int) -> int:
                nums.sort()
                length = len(nums)
                left, right = 0, length - 1
                while left <= right:
                    i = left + (right - left) // 2
                    val = nums[i]
                    if val > original:
                        right = i - 1
                    elif val == original:
                        original *= 2
                        left = i + 1
                        right = length - 1
                    else:
                        left = i + 1
                return original
        

        4.7.361 - 2025-08-17 17:56:42 +0300 MSK

        Keep Multiplying Found Values by Two

        Code

        class Solution:
            def findFinalValue(self, nums: List[int], original: int) -> int:
                nums = set(nums)
                while original in nums:
                    original *= 2
                return original
        

        4.7.362 - 2025-08-17 17:28:49 +0300 MSK

        Count Elements With Strictly Smaller and Greater Elements

        Code

        class Solution:
            def countElements(self, nums: List[int]) -> int:
                if len(nums) < 3:
                    return 0
                nums.sort()
                res = 0
                prev, cur, cur_count = None, nums[0], 1
                for num in nums:
                    if num == cur:
                        cur_count += 1
                    elif prev is None:
                        prev = cur
                        cur = num
                        cur_count = 1
                    else:
                        res += cur_count
                        prev = cur
                        cur = num
                        cur_count = 1
                return res
        

        4.7.363 - 2025-08-17 17:16:59 +0300 MSK

        Minimum Cost of Buying Candies With Discount

        Code

        class Solution:
            def minimumCost(self, cost: List[int]) -> int:
                cost.sort()
                res = 0
                while cost:
                    if len(cost) > 2:
                        res += cost.pop() + cost.pop()
                        cost.pop()
                    else:
                        res += cost.pop()
                return res
        

        4.7.364 - 2025-08-17 17:04:01 +0300 MSK

        Divide a String Into Groups of Size k

        Code

        class Solution:
            def divideString(self, s: str, k: int, fill: str) -> List[str]:
                res = []
                cur = []
                for char in s:
                    cur.append(char)
                    if len(cur) == k:
                        res.append("".join(cur))
                        cur.clear()
                if cur and len(cur) < k:
                    cur.append(fill * (k - len(cur)))
                    res.append("".join(cur))
                    cur.clear()
                return res
        

        4.7.365 - 2025-08-17 16:00:07 +0300 MSK

        Check if Every Row and Column Contains All Numbers

        Code

        class Solution:
            def checkValid(self, matrix: List[List[int]]) -> bool:
                length = len(matrix)
                rows = bytearray(length + 1)
                cols = bytearray(length + 1)
                for row in range(length):    
                    for col in range(length):
                        row_col, col_row = matrix[row][col], matrix[col][row]
                        rows[row_col] += 1
                        cols[col_row] += 1
                        if rows[row_col] > 1 or cols[col_row] > 1:
                            return False
                    for i in range(length + 1):
                        rows[i] = 0
                        cols[i] = 0
                return True
        

        4.7.366 - 2025-08-17 13:53:56 +0300 MSK

        Capitalize the Title

        Code

        class Solution:
            def capitalizeTitle(self, title: str) -> str:
                res = []
                cur = []
                for char in itertools.chain(title, " "):
                    if char != " ":
                        cur.append(char)
                        continue
                    for i in range(len(cur)):
                        cur[i] = cur[i].lower()
                    if len(cur) > 2:
                        cur[0] = cur[0].upper()
                    res.append("".join(cur))
                    cur.clear()
                return " ".join(res) 
        

        4.7.367 - 2025-08-17 13:41:15 +0300 MSK

        Check if All A’s Appears Before All B’s

        Code

        class Solution:
            def checkString(self, s: str) -> bool:
                found_a = False
                found_b = False
                for char in s:
                    if char == "a":
                        if found_b:
                            return False
                        if not found_a:
                            found_a = True
                    else:
                        if not found_b:
                            found_b = True
                return True
        

        4.7.368 - 2025-08-17 13:38:02 +0300 MSK

        A Number After a Double Reversal

        Code

        class Solution:
            def isSameAfterReversals(self, num: int) -> bool:
                if num == 0:
                    return True
                return num % 10 != 0
        

        4.7.369 - 2025-08-17 13:36:24 +0300 MSK

        Maximum Number of Words Found in Sentences

        Code

        class Solution:
            def mostWordsFound(self, sentences: List[str]) -> int:
                res = 0
                for sentence in sentences:
                    count = sentence.count(" ") + 1
                    if count > res:
                        res = count
                return res
        

        4.7.370 - 2025-08-17 13:34:11 +0300 MSK

        Rings and Rods

        Code

        class Solution:
            def countPoints(self, rings: str) -> int:
                rods = [(False, False, False)] * 10
                res = 0
                for i in range(0, len(rings), 2):
                    rod = int(rings[i + 1])
                    color = rings[i]
                    has_red, has_green, has_blue = rods[rod]
                    if color == "R":
                        has_red = True
                    elif color == "G":
                        has_green = True
                    else:
                        has_blue = True
                    rods[rod] = (has_red, has_green, has_blue)
                for vals in rods:
                    if all(vals):
                        res += 1
                return res
        

        4.7.371 - 2025-08-17 13:25:54 +0300 MSK

        Find Subsequence of Length K With the Largest Sum

        Code

        class Solution:
            def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
                length = len(nums)
                for i in range(length):
                    nums[i] = (i, nums[i])
                nums.sort(key=lambda num: -num[1])
                while len(nums) > k:
                    nums.pop()
                nums.sort()
                for i in range(k):
                    nums[i] = nums[i][1]
                return nums
        

        4.7.372 - 2025-08-17 13:10:43 +0300 MSK

        Finding 3-Digit Even Numbers

        Code

        class Solution:
            def findEvenNumbers(self, digits: List[int]) -> List[int]:
                res = []
                freq = Counter(digits)  
                for i in range(100, 1000, 2):
                    freq1 = Counter([int(d) for d in str(i)])
                    if all(freq[d] >= freq1[d] for d in freq1.keys()):
                        res.append(i)
                return res
        

        4.7.373 - 2025-08-17 12:55:05 +0300 MSK

        Find Target Indices After Sorting Array

        Code

        class Solution:
            def targetIndices(self, nums: List[int], target: int) -> List[int]:
                count_eq = 0
                count_less = 0
                for num in nums:
                    if num == target:
                        count_eq += 1
                    elif num < target:
                        count_less += 1
                return tuple(range(count_less, count_less + count_eq))
        

        4.7.374 - 2025-08-17 12:47:03 +0300 MSK

        Find Target Indices After Sorting Array

        Code

        class Solution:
            def targetIndices(self, nums: List[int], target: int) -> List[int]:
                nums.sort()
                if nums[0] > target or nums[-1] < target:
                    return []
                res = []
                for i, num in enumerate(nums):
                    if num == target:
                        res.append(i)
                return res
        

        4.7.375 - 2025-08-17 12:39:05 +0300 MSK

        Count Common Words With One Occurrence

        Code

        class Solution:
            def countWords(self, words1: List[str], words2: List[str]) -> int:
                freqs = defaultdict(lambda: (0, 0))
                for word in words1:
                    freq1, _ = freqs[word]
                    if freq1 in (0, 1):
                        freqs[word] = (freq1 + 1, 0)
                for word in words2:
                    freq1, freq2 = freqs[word]
                    if freq2 in (0, 1):
                        freqs[word] = (freq1, freq2 + 1)
                res = 0
                for freq1, freq2 in freqs.values():
                    if freq1 == freq2 == 1:
                        res += 1
                return res
                
        

        4.7.376 - 2025-08-17 11:54:12 +0300 MSK

        Two Furthest Houses With Different Colors

        Code

        class Solution:
            def maxDistance(self, colors: List[int]) -> int:
                prev, res = math.inf, 0
                start = colors[0]
                for i, color in enumerate(colors):
                    if color != start:
                        res = i
                        prev = min(prev, i)
                    else:
                        res = max(res, i - prev)
                return res
        

        4.7.377 - 2025-08-17 09:23:21 +0300 MSK

        New 21 Game

        Code

        class Solution:
            def new21Game(self, n: int, k: int, maxPts: int) -> float:
                dp = [0] * (n + 1)
                dp[0] = 1
                s = 1 if k > 0 else 0
                for i in range(1, n + 1):
                    dp[i] = s / maxPts
                    if i < k:
                        s += dp[i]
                    if i - maxPts >= 0 and i - maxPts < k:
                        s -= dp[i - maxPts]
                return sum(dp[k:])
        

        4.7.378 - 2025-08-16 18:43:20 +0300 MSK

        Check Whether Two Strings are Almost Equivalent

        Code

        class Solution:
            def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
                freqs = [0] * 26
                for char in word1:
                    freqs[ord(char) - 97] += 1
                for char in word2:
                    freqs[ord(char) - 97] -= 1
                for freq in freqs:
                    if freq > 3 or freq < -3:
                        return False
                return True
        

        4.7.379 - 2025-08-16 16:51:28 +0300 MSK

        Count Vowel Substrings of a String

        Code

        from collections import defaultdict
        
        class Solution:
            def countVowelSubstrings(self, word):
                vowels_map = {'a': True, 'e': True, 'i': True, 'o': True, 'u': True}
                len_word = len(word)
                left_index = 0
                right_index = 0
                ret_val = 0
                char_to_freq_map = defaultdict(int)
                i = 0
                while i < len_word:
                    c = word[i]
                    if c in vowels_map.keys():
                        char_to_freq_map[c] += 1
                        while set(char_to_freq_map.keys()) == set(vowels_map.keys()):
                            c = word[right_index]
                            char_to_freq_map[c] -= 1
                            if (char_to_freq_map[c] <= 0):
                                char_to_freq_map.pop(c)
                            right_index += 1
                        ret_val += (right_index - left_index)
                    else:
                        char_to_freq_map.clear()
                        left_index = i + 1
                        right_index = i + 1
                    i += 1
                return ret_val
        

        4.7.380 - 2025-08-16 16:11:23 +0300 MSK

        Smallest Index With Equal Value

        Code

        class Solution:
            def smallestEqual(self, nums: List[int]) -> int:
                for i, num in enumerate(nums):
                    if i % 10 == num:
                        return i
                return -1
        

        4.7.381 - 2025-08-16 14:42:51 +0300 MSK

        Kth Distinct String in an Array

        Code

        class Solution:
            def kthDistinct(self, arr: List[str], k: int) -> str:
                freqs = defaultdict(int)
                for string in arr:
                    if freqs[string] in (0, 1):
                        freqs[string] += 1
                for string in arr:
                    if freqs[string] == 1:
                        if k == 1:
                            return string
                        k -= 1
                return ""
        

        4.7.382 - 2025-08-16 14:31:57 +0300 MSK

        Number of Valid Words in a Sentence

        Code

        class Solution:
            def countValidWords(self, sentence: str) -> int:
                def is_valid_word(token):
                    len_token = len(token)
                    
                    i = 0
                    while (i < len_token):
                        c = token[i]
                        if (ord(c) not in range(ord('a'), ord('z') + 1)
                            and c != '-'
                            and c not in ('!', '.', ',')):
                            return False
                        elif (c == '-'
                              and i > 1
                              and not token[:i].isalpha()):
                            return False
                        elif (c == '-'
                              and i < len_token - 1
                              and (not token[i+1:].isalpha() and not (token[i+1:-1].isalpha() and token[-1] in ('!', '.', ',')))):
                            return False
                        elif (c == '-'
                              and (i == 0 or i == len_token-1)):
                            return False
                        elif (c in ('!', '.', ',')
                              and i < len_token - 1):
                            return False
        
                        i += 1
        
                    return True
        
                tokens = [t for t in sentence.split(' ') if t != '']
                count_valid_words = 0
                for token in tokens:
                    print(token, is_valid_word(token))
                    if (is_valid_word(token)):
                        count_valid_words += 1
                
                return count_valid_words
        

        4.7.383 - 2025-08-16 14:30:59 +0300 MSK

        Check if Numbers Are Ascending in a Sentence

        Code

        class Solution:
            def areNumbersAscending(self, s: str) -> bool:
                cur = []
                prev = 0
                for char in itertools.chain(s, " "):
                    if char.isdigit():
                        cur.append(char)
                    elif cur:
                        val = 0
                        count = 0
                        while cur:
                            val += int(cur.pop()) * (10 ** count)
                            count += 1
                        if val <= prev:
                            return False
                        prev = val
                return True
        

        4.7.384 - 2025-08-16 14:27:06 +0300 MSK

        Two Out of Three

        Code

        class Solution:
            def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
                freqs = [(False, False, False)] * 102
                for num in nums1:
                    freqs[num] = (True, False, False)
                for num in nums2:
                    stat1, stat2, _ = freqs[num]
                    if not stat2:
                        freqs[num] = (stat1, True, False)
                for num in nums3:
                    stat1, stat2, stat3 = freqs[num]
                    if not stat3:
                        freqs[num] = (stat1, stat2, True) 
                nums1.clear()
                for num in range(1, len(freqs)):
                    if sum(freqs[num]) >= 2:
                        nums1.append(num)
                return nums1
        

        4.7.385 - 2025-08-16 14:19:48 +0300 MSK

        Minimum Moves to Convert String

        Code

        class Solution:
            def minimumMoves(self, s: str) -> int:
                i = 0
                length = len(s)
                res = 0
                while i < length:
                    if s[i] == "X":
                        res += 1
                        i += 3
                    else:
                        i += 1
                return res 
        

        4.7.386 - 2025-08-16 14:16:53 +0300 MSK

        Convert 1D Array Into 2D Array

        Code

        class Solution:
            def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
                i = 0
                if len(original) != m * n:
                    return []
                res = [[None] * n for _ in range(m)]
                for row in range(m):
                    for col in range(n):
                        res[row][col] = original[i]
                        i += 1
                return res
        

        4.7.387 - 2025-08-16 14:14:34 +0300 MSK

        Maximum Difference Between Increasing Elements

        Code

        class Solution:
            def maximumDifference(self, nums: List[int]) -> int:
                res, left = -1, nums[0]
                for num in nums[1:]:
                    if num > left:
                        diff = num - left
                        if diff > res:
                            res = diff
                    else:
                        left = num
                return res
        

        4.7.388 - 2025-08-16 14:05:37 +0300 MSK

        Final Value of Variable After Performing Operations

        Code

        class Solution:
            def finalValueAfterOperations(self, operations: List[str]) -> int:
                res = 0
                for op in operations:
                    if op.startswith("++") or op.endswith("++"):
                        res += 1
                    else:
                        res -= 1
                return res
        

        4.7.389 - 2025-08-16 14:04:12 +0300 MSK

        Count Number of Pairs With Absolute Difference K

        Code

        class Solution:
            def countKDifference(self, nums: List[int], k: int) -> int:
                freqs = [0] * 102
                count = 0
                for num in nums:
                    freqs[num] += 1
                for num in nums:
                    freqs[num] = max(freqs[num] - 1, 0)
                    target = num + k
                    for target in (num - k, num + k):
                        if target >= 0 and target < 102 and freqs[target] > 0:
                            count += freqs[target]
                return count
        

        4.7.390 - 2025-08-16 13:53:07 +0300 MSK

        Count Special Quadruplets

        Code

        class Solution:
            def countQuadruplets(self, nums: List[int]) -> int:
                count = 0
                numbers = defaultdict(list)
                length = len(nums)
                for i in range(length - 1):
                    for j in range(i + 1, length):
                        numbers[nums[i] + nums[j]].append(j)
                for i in range(2, length - 1):
                    for j in range(i + 1, length):
                        target = nums[j] - nums[i]
                        for idx in numbers[target]:
                            if i > idx:
                                count += 1
                return count
        

        4.7.391 - 2025-08-16 13:39:08 +0300 MSK

        Find the Middle Index in Array

        Code

        class Solution:
            def findMiddleIndex(self, nums: List[int]) -> int:
                left, right = 0, sum(nums)
                for i, num in enumerate(nums):
                    right -= num
                    if left == right:
                        return i
                    left += num
                return -1
        

        4.7.392 - 2025-08-16 13:35:39 +0300 MSK

        Minimum Difference Between Highest and Lowest of K Scores

        Code

        class Solution:
            def minimumDifference(self, nums: list[int], k: int) -> int:
                if (k < 2 or k > len(nums)):
                    return 0
                nums.sort()
                lowest = float('inf')
                for i in range(len(nums) - k + 1):
                    diff = nums[i + k - 1] - nums[i]
                    if diff < lowest:
                        lowest = diff
                return lowest
        

        4.7.393 - 2025-08-16 13:22:50 +0300 MSK

        Find Greatest Common Divisor of Array

        Code

        class Solution:
            def findGCD(self, nums: List[int]) -> int:
                nums.sort()
                small, big = nums[0], nums[-1]
                for i in range(1, small + 1):
                    if small % i != 0:
                        continue
                    val = small // i
                    if big % val == 0:
                        return val
                raise Exception
        

        4.7.394 - 2025-08-16 13:15:31 +0300 MSK

        Employees Whose Manager Left the Company

        Code

        SELECT
            employee_id
        FROM
            Employees
        WHERE
            manager_id NOT IN (
                SELECT
                    employee_id
                FROM
                    Employees
            ) 
            AND salary < 30000
        ORDER BY
            employee_id
        

        4.7.395 - 2025-08-16 13:13:30 +0300 MSK

        Minimum Time to Type Word Using Special Typewriter

        Code

        class Solution:
            def minTimeToType(self, word: str) -> int:
                pos = 97
                res = 0
                for char in word:
                    cur_pos = ord(char)
                    diff = abs(cur_pos - pos) 
                    res += min(diff, 26 - diff) + 1
                    pos = cur_pos
                return res
        

        4.7.396 - 2025-08-16 12:59:52 +0300 MSK

        Number of Strings That Appear as Substrings in Word

        Code

        class Solution:
            def numOfStrings(self, patterns: List[str], word: str) -> int:
                count = 0
                for pattern in patterns:
                    if pattern in word:
                        count += 1
                return count
        

        4.7.397 - 2025-08-16 12:54:52 +0300 MSK

        Employees With Missing Information

        Code

        SELECT 
            COALESCE(
                t1.employee_id, 
                t2.employee_id
            ) AS employee_id
        FROM
            Employees t1 
        FULL JOIN
            Salaries t2
        ON 
            t1.employee_id = t2.employee_id
        WHERE 
            t1.name IS NULL 
            OR t2.salary IS NULL
        ORDER BY 
            employee_id;
        

        4.7.398 - 2025-08-16 12:42:27 +0300 MSK

        Check If String Is a Prefix of Array

        Code

        class Solution:
            def isPrefixString(self, s: str, words: List[str]) -> bool:
                i = 0
                length = len(s)
                for word in words:
                    if i >= length:
                        return True
                    word_length = len(word)
                    if word_length > length - i:
                        return False
                    if word != s[i:i+word_length]:
                        return False
                    i += word_length
                return i >= length
        

        4.7.399 - 2025-08-16 12:24:35 +0300 MSK

        Three Divisors

        Code

        class Solution:
            def isThree(self, n: int) -> bool:
                count = 1
                for num in range(2, n // 2 + 1):
                    if n % num == 0:
                        count += 2
                    if count > 3:
                        break
                return count == 3
        

        4.7.400 - 2025-08-16 12:19:08 +0300 MSK

        Sum of Digits of String After Convert

        Code

        class Solution:
            def getLucky(self, s: str, k: int) -> int:
                def trans(val: int, count: int) -> int:
                    if count == 0:
                        return val
                    res = 0
                    while val > 0:
                        res += val % 10
                        val //= 10
                    return trans(res, count - 1)
                val = 0
                for char in s:
                    val += trans(ord(char) - 97 + 1, 1)
                return trans(val, k - 1)
        

        4.7.401 - 2025-08-16 12:12:54 +0300 MSK

        Check if All Characters Have Equal Number of Occurrences

        Code

        class Solution:
            def areOccurrencesEqual(self, s: str) -> bool:
                freqs = defaultdict(int)
                for char in s:
                    freqs[char] += 1
                target = freqs[s[0]]
                for freq in freqs.values():
                    if freq != target:
                        return False
                return True
        

        4.7.402 - 2025-08-16 12:11:17 +0300 MSK

        Maximum Number of Words You Can Type

        Code

        class Solution:
            def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
                ignore = False
                res = 0
                for char in itertools.chain(text, " "):
                    if char == " ":
                        if ignore:
                            ignore = False
                        else:
                            res += 1
                    elif char in brokenLetters:
                        ignore = True
                return res
        

        4.7.403 - 2025-08-16 12:07:23 +0300 MSK

        Concatenation of Array

        Code

        class Solution:
            def getConcatenation(self, nums: List[int]) -> List[int]:
                for i in range(len(nums)):
                    nums.append(nums[i])
                return nums
        

        4.7.404 - 2025-08-16 12:06:11 +0300 MSK

        Count Square Sum Triples

        Code

        class Solution:
            def countTriples(self, n: int) -> int:
                res = 0
                for a in range(1, n):
                    for b in range(a + 1, n):
                        c = math.sqrt(a * a + b * b)
                        if c % 1 == 0 and c <= n:
                            res += 2
                return res
        

        4.7.405 - 2025-08-16 11:58:38 +0300 MSK

        Build Array from Permutation

        Code

        class Solution:
            def buildArray(self, nums: List[int]) -> List[int]:
                length = len(nums)
                for i in range(length):
                    val = nums[i] % 1000
                    res = 1000 * (nums[val] % 1000)
                    nums[i] = res + val
                for i in range(length):
                    nums[i] //= 1000
                return nums
        

        4.7.406 - 2025-08-16 11:50:13 +0300 MSK

        Build Array from Permutation

        Code

        class Solution:
            def buildArray(self, nums: List[int]) -> List[int]:
                res = [None] * len(nums)
                for i, num in enumerate(nums):
                    res[i] = nums[num]
                return res
        

        4.7.407 - 2025-08-16 11:32:58 +0300 MSK

        Remove One Element to Make the Array Strictly Increasing

        Code

        class Solution:
            def canBeIncreasing(self, nums: List[int]) -> bool:
                removed = False
                length = len(nums)
                for i in range(length - 1):
                    cur, nxt = nums[i], nums[i + 1]
                    if nxt > cur:
                        continue
                    if removed:
                        return False
                    removed = True
                    if (
                        i > 0 and nums[i - 1] >= nxt
                    ) and (
                        i + 2 < length and cur >= nums[i + 2]
                    ):
                        return False
                return True
        

        4.7.408 - 2025-08-16 11:14:35 +0300 MSK

        Check if All the Integers in a Range Are Covered

        Code

        class Solution:
            def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
                cov = [False] * (right - left + 1)
                for start, end in ranges:
                    for num in range(max(left, start), min(end, right) + 1):
                        i = num - left
                        if not cov[i]:
                            cov[i] = True
                return False not in cov
        

        4.7.409 - 2025-08-16 11:13:51 +0300 MSK

        Check if All the Integers in a Range Are Covered

        Code

        class Solution:
            def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
                cov = [False] * (right - left + 1)
                for start, end in ranges:
                    for num in range(max(left, start), min(end, right) + 1):
                        cov[num - left] = True
                return False not in cov
        

        4.7.410 - 2025-08-16 11:09:17 +0300 MSK

        The Latest Login in 2020

        Code

        SELECT 
            user_id, 
            MAX(time_stamp) AS last_stamp
        FROM 
            Logins 
        WHERE 
            time_stamp >= '2020-01-01'
            AND time_stamp < '2021-01-01'
        GROUP BY 
            user_id
        

        4.7.411 - 2025-08-16 10:49:39 +0300 MSK

        Determine Whether Matrix Can Be Obtained By Rotation

        Code

        class Solution:
            def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
                length = len(mat)
                count_0, count_90, count_180, count_270 = 0, 0, 0, 0
                for i in range(length):
                    for j in range(length):
                        val = mat[i][j]
                        if val == target[i][j]:
                            count_0 += 1
                        if val == target[j][length - i - 1]:
                            count_90 += 1
                        if val == target[length - i - 1][length - j - 1]:
                            count_180 += 1
                        if val == target[length - j - 1][i]:
                            count_270 += 1
                return length * length in {count_0, count_90, count_180, count_270}
        

        4.7.412 - 2025-08-16 10:22:08 +0300 MSK

        Check if Word Equals Summation of Two Words

        Code

        class Solution:
            def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
                def count(word: str) -> int:
                    length = len(word)
                    res = 0
                    for i in reversed(range(length)):
                        res += (ord(word[i]) - 97) * (10 ** (length - i - 1))
                    return res
                return count(firstWord) + count(secondWord) == count(targetWord)
        

        4.7.413 - 2025-08-16 10:19:18 +0300 MSK

        Check if Word Equals Summation of Two Words

        Code

        class Solution:
            def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
                digits = []
                def count(word: str) -> int:
                    for char in word:
                        digits.append(ord(char) - 97)
                    res = 0
                    count = 0
                    while digits:
                        res += digits.pop() * (10 ** count)
                        count += 1
                    return res
                return count(firstWord) + count(secondWord) == count(targetWord)
        

        4.7.414 - 2025-08-16 10:09:43 +0300 MSK

        Maximum 69 Number

        Code

        class Solution:
            def maximum69Number (self, num: int) -> int:
                digits = []
                while num > 0:
                    digits.append(num % 10)
                    num //= 10
                digits.reverse()
                for i in range(len(digits)):
                    if digits[i] == 6:
                        digits[i] = 9
                        break
                res = 0
                count = 0
                while digits:
                    res += digits.pop() * (10 ** count)
                    count += 1
                return res
        

        4.7.415 - 2025-08-15 17:31:44 +0300 MSK

        Substrings of Size Three with Distinct Characters

        Code

        class Solution:
            def countGoodSubstrings(self, s: str) -> int:
                res = 0
                for i in range(len(s) - 2):
                    char1, char2, char3 = s[i:i+3]
                    if char1 != char2 and char1 != char3 and char2 != char3:
                        res += 1
                return res
        

        4.7.416 - 2025-08-15 16:57:42 +0300 MSK

        Calculate Special Bonus

        Code

        SELECT
            employee_id,
            (
                CASE 
                    WHEN
                        employee_id % 2 != 0
                        AND NOT STARTS_WITH(name, 'M')
                    THEN
                        salary
                    ELSE
                        0
                END
        
            ) AS "bonus"
        FROM
            Employees
        ORDER BY
            employee_id
        

        4.7.417 - 2025-08-15 16:43:07 +0300 MSK

        Longer Contiguous Segments of Ones than Zeros

        Code

        class Solution:
            def checkZeroOnes(self, s: str) -> bool:
                max_length = [0, 0]
                cur = 0
                prev = -1
                for char in s:
                    val = int(char)
                    if val == prev:
                        cur += 1
                    else:
                        cur = 1
                    if cur > max_length[val]:
                        max_length[val] = cur
                    prev = val
                return max_length[1] > max_length[0]
        

        4.7.418 - 2025-08-15 16:35:39 +0300 MSK

        Sorting the Sentence

        Code

        class Solution:
            def sortSentence(self, s: str) -> str:
                res = [None] * 9
                cur = []
                for char in s:
                    if char.isalpha():
                        cur.append(char)
                    elif char.isdigit():
                        res[int(char) - 1] = "".join(cur)
                        cur.clear()
                return " ".join(word for word in res if word is not None)
        

        4.7.419 - 2025-08-15 16:30:08 +0300 MSK

        Maximum Population Year

        Code

        class Solution:
            def maximumPopulation(self, logs: List[List[int]]) -> int:
                population = [0] * 102
                max_population = 0
                for birth, death in logs:
                    for year in range(birth, death):
                        i = year - 1950
                        new_population = population[i] + 1
                        population[i] = new_population
                        if new_population > max_population:
                            max_population = new_population
                for i, count in enumerate(population):
                    if count == max_population:
                        return 1950 + i
                raise Exception
        

        4.7.420 - 2025-08-15 16:25:44 +0300 MSK

        Minimum Distance to the Target Element

        Code

        class Solution:
            def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
                length = len(nums)
                dist = 0
                while dist < length:
                    left, right = start - dist, start + dist
                    if left >= 0 and nums[left] == target:
                        return dist
                    if right < length and nums[right] == target:
                        return dist
                    dist += 1
                raise Exception
        

        4.7.421 - 2025-08-15 16:20:07 +0300 MSK

        Replace All Digits with Characters

        Code

        class Solution:
            def replaceDigits(self, s: str) -> str:
                res = []
                for i in range(0, len(s) - 1, 2):
                    char, digit = s[i], int(s[i + 1])
                    res.append(char)
                    res.append(chr(ord(char) + digit))
                if len(s) % 2 != 0:
                    res.append(s[-1])
                return "".join(res)
        

        4.7.422 - 2025-08-15 16:13:25 +0300 MSK

        Sum of Digits in Base K

        Code

        class Solution:
            def sumBase(self, n: int, k: int) -> int:
                digits = []
                while n > 0:
                    digits.append(n % k)
                    n //= k
                return sum(digits)
        

        4.7.423 - 2025-08-15 16:11:57 +0300 MSK

        Check if the Sentence Is Pangram

        Code

        class Solution:
            def checkIfPangram(self, sentence: str) -> bool:
                freqs = [0] * 26
                for char in sentence:
                    freqs[ord(char) - 97] += 1
                return 0 not in freqs
        

        4.7.424 - 2025-08-15 16:11:03 +0300 MSK

        Minimum Operations to Make the Array Increasing

        Code

        class Solution:
            def minOperations(self, nums: List[int]) -> int:
                res = 0
                prev = nums[0]
                for num in nums[1:]:
                    if num > prev:
                        prev = num
                    else:
                        new = prev + 1
                        res += new - num
                        prev = new
                return res
        

        4.7.425 - 2025-08-15 16:06:24 +0300 MSK

        Truncate Sentence

        Code

        class Solution:
            def truncateSentence(self, s: str, k: int) -> str:
                res = s.split(" ")
                while len(res) > k:
                    res.pop()
                return " ".join(res)
        

        4.7.426 - 2025-08-15 16:05:32 +0300 MSK

        Truncate Sentence

        Code

        class Solution:
            def truncateSentence(self, s: str, k: int) -> str:
                res = []
                cur = []
                for char in itertools.chain(s, " "):
                    if char.isalpha():
                        cur.append(char)
                    else:
                        res.append("".join(cur))
                        cur.clear()
                        if len(res) == k:
                            return " ".join(res)
                raise Exception
        

        4.7.427 - 2025-08-15 16:03:03 +0300 MSK

        Determine Color of a Chessboard Square

        Code

        class Solution:
            def squareIsWhite(self, coordinates: str) -> bool:
                col = ord(coordinates[0]) - 97
                row = int(coordinates[1])
                if row % 2 == 0:
                    return col % 2 == 0
                return col % 2 != 0
                
        

        4.7.428 - 2025-08-15 15:54:30 +0300 MSK

        Number of Different Integers in a String

        Code

        class Solution:
            def numDifferentIntegers(self, word: str) -> int:
                enc = set()
                cur = []
                for char in itertools.chain(word, "a"):
                    if char.isalpha():
                        if cur:
                            count = 0
                            num = 0
                            while cur:
                                num += cur.pop() * (10 ** count)
                                count += 1
                            enc.add(num)
                    else:
                        cur.append(int(char))
                return len(enc)
                
                    
        

        4.7.429 - 2025-08-15 15:47:22 +0300 MSK

        Maximum Ascending Subarray Sum

        Code

        class Solution:
            def maxAscendingSum(self, nums: List[int]) -> int:
                max_sum, cur_sum, prev = nums[0], nums[0], nums[0]
                for num in nums[1:]:
                    if num > prev:
                        cur_sum += num
                    else:
                        cur_sum = num
                    if cur_sum > max_sum:
                        max_sum = cur_sum
                    prev = num
                return max_sum
        

        4.7.430 - 2025-08-15 15:44:11 +0300 MSK

        Second Largest Digit in a String

        Code

        class Solution:
            def secondHighest(self, s: str) -> int:
                num1, num2 = -1, -1
                for char in s:
                    if not char.isdigit():
                        continue
                    num = int(char)
                    if num > num2:
                        num1, num2 = num2, num
                    elif num != num2 and num > num1:
                        num1 = num
                return num1
        

        4.7.431 - 2025-08-15 15:38:40 +0300 MSK

        Rearrange Products Table

        Code

        (
            SELECT 
                product_id,
                'store1' AS store,
                store1 AS price
            FROM 
                Products
            WHERE 
                store1 IS NOT NULL
        ) UNION (
            SELECT 
                product_id,
                'store2' AS store,
                store2 AS price
            FROM 
                Products
            WHERE 
                store2 IS NOT NULL
        ) UNION (
            SELECT 
                product_id,
               'store3' AS store,
               store3 AS price
            FROM 
                Products
            WHERE 
                store3 IS NOT NULL
        )
        ORDER BY 
            product_id, 
            store;
        

        4.7.432 - 2025-08-15 15:32:17 +0300 MSK

        Find Center of Star Graph

        Code

        class Solution:
            def findCenter(self, edges: List[List[int]]) -> int:
                num1, num2 = edges[0]
                num3, num4 = edges[1]
                if num1 == num3 or num1 == num4:
                    return num1
                return num2
        

        4.7.433 - 2025-08-15 15:28:53 +0300 MSK

        Check if One String Swap Can Make Strings Equal

        Code

        class Solution:
            def areAlmostEqual(self, s1: str, s2: str) -> bool:
                if s1 == s2:
                    return True
                length = len(s1)
                if length != len(s2):
                    return False
                i1, i2 = -1, -1
                for i, (char1, char2) in enumerate(zip(s1, s2)):
                    if char1 == char2:
                        continue
                    if i1 == -1:
                        i1 = i
                    elif i2 == -1:
                        i2 = i
                    else:
                        return False
                if i2 == -1:
                    return False
                return s1[i1] == s2[i2] and s1[i2] == s2[i1]
        

        4.7.434 - 2025-08-15 15:12:21 +0300 MSK

        Primary Department for Each Employee

        Code

        SELECT 
            employee_id, 
            department_id
        FROM 
            (
                SELECT 
                    employee_id,
                    department_id,
                    primary_flag,
                    COUNT(employee_id) OVER(
                        PARTITION BY 
                            employee_id
                    ) AS employee_count
                FROM 
                    Employee
            ) EmployeePartition
        WHERE 
            employee_count = 1 
            OR primary_flag = 'Y';
        

        4.7.435 - 2025-08-15 15:04:18 +0300 MSK

        Check if Binary String Has at Most One Segment of Ones

        Code

        class Solution:
            def checkOnesSegment(self, s: str) -> bool:
                enc = False
                for char in s:
                    if char == "1":
                        if enc:
                            return False
                    elif not enc:
                        enc = True
                return True
        

        4.7.436 - 2025-08-15 15:03:12 +0300 MSK

        Check if Binary String Has at Most One Segment of Ones

        Code

        class Solution:
            def checkOnesSegment(self, s: str) -> bool:
                enc = False
                for char in s[1:]:
                    if char == "1" and enc:
                        return False
                    elif char == "1":
                        continue
                    enc = True
                return True
        

        4.7.437 - 2025-08-15 14:37:22 +0300 MSK

        Count Items Matching a Rule

        Code

        class Solution:
            def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
                count = 0
                for type, color, name in items:
                    if (
                        (ruleKey == "type" and ruleValue == type)
                        or (ruleKey == "color" and ruleValue == color)
                        or (ruleKey == "name" and ruleValue == name)
                    ):
                        count += 1
                return count 
        

        4.7.438 - 2025-08-15 14:34:58 +0300 MSK

        Recyclable and Low Fat Products

        Code

        SELECT
            Products.product_id
        FROM
            Products
        WHERE
            Products.low_fats = 'Y'
            AND Products.recyclable = 'Y';
        

        4.7.439 - 2025-08-15 14:33:22 +0300 MSK

        Check if Array Is Sorted and Rotated

        Code

        class Solution:
            def check(self, nums: List[int]) -> bool:
                prev = nums[0]
                count = 0
                for num in nums[1:]:
                    if num >= prev:
                        pass
                    elif count == 0:
                        count = 1
                    else:
                        return False
                    prev = num
                if count == 0:
                    return True
                return nums[0] >= nums[-1]
        

        4.7.440 - 2025-08-15 14:31:10 +0300 MSK

        Check if Array Is Sorted and Rotated

        Code

        class Solution:
            def check(self, nums: List[int]) -> bool:
                prev = nums[0]
                new_start = 0
                for num in nums[1:]:
                    if num >= prev:
                        pass
                    elif new_start == 0:
                        new_start = num
                    else:
                        return False
                    prev = num
                if new_start == 0:
                    return True
                return nums[0] >= nums[-1]
        

        4.7.441 - 2025-08-15 14:21:42 +0300 MSK

        Sum of Unique Elements

        Code

        class Solution:
            def sumOfUnique(self, nums: List[int]) -> int:
                enc = [0] * 101
                res = 0
                for num in nums:
                    count = enc[num]
                    if count == 1:
                        res -= num
                        enc[num] = 2
                    elif count == 0:
                        res += num
                        enc[num] = 1
                return res
        

        4.7.442 - 2025-08-15 14:17:27 +0300 MSK

        Maximum Number of Balls in a Box

        Code

        class Solution:
            def countBalls(self, lowLimit: int, highLimit: int) -> int:
                freqs = [0] * 100
                max_freq = 0
                for num in range(lowLimit, highLimit + 1):
                    box = 0
                    while num > 0:
                        box += num % 10
                        num //= 10
                    freqs[box] += 1
                    max_freq = max(max_freq, freqs[box])
                return max_freq
        

        4.7.443 - 2025-08-15 14:14:49 +0300 MSK

        Maximum Number of Balls in a Box

        Code

        class Solution:
            def countBalls(self, lowLimit: int, highLimit: int) -> int:
                freqs = defaultdict(int)
                max_freq = 0
                for num in range(lowLimit, highLimit + 1):
                    box = 0
                    while num > 0:
                        box += num % 10
                        num //= 10
                    freqs[box] += 1
                    max_freq = max(max_freq, freqs[box])
                return max_freq
        

        4.7.444 - 2025-08-15 13:38:16 +0300 MSK

        Find Total Time Spent by Each Employee

        Code

        SELECT
            Employees.event_day AS "day",
            Employees.emp_id,
            SUM(Employees.out_time - Employees.in_time) AS "total_time"
        FROM
            Employees
        GROUP BY
            Employees.event_day,
            Employees.emp_id
        

        4.7.445 - 2025-08-15 13:31:41 +0300 MSK

        Latest Time by Replacing Hidden Digits

        Code

        class Solution:
            def maximumTime(self, time: str) -> str:
                hours, minutes = time.split(":")
                hour1, hour2 = hours
                minute1, minute2 = minutes
                if hour1 == "?" and hour2 == "?":
                    hour1, hour2 = "2", "3"
                elif hour1 == "?" and hour2 < "4":
                    hour1 = "2"
                elif hour1 == "?":
                    hour1 = "1"
                elif hour1 == "2" and hour2 == "?":
                    hour2 = "3"
                elif hour2 == "?":
                    hour2 = "9"
                if minute1 == "?":
                    minute1 = "5"
                if minute2 == "?":
                    minute2 = "9"
                return ":".join(("".join((hour1, hour2)), "".join((minute1, minute2)))) 
        

        4.7.446 - 2025-08-15 13:23:40 +0300 MSK

        The Number of Employees Which Report to Each Employee

        Code

        SELECT 
            managers.employee_id, 
            managers.name, 
            COUNT(reports.employee_id) AS reports_count, 
            ROUND(AVG(reports.age)) AS average_age
        FROM 
            Employees managers
        INNER JOIN 
            Employees reports
        ON
            managers.employee_id = reports.reports_to
        GROUP BY 
            managers.employee_id, 
            managers.name
        ORDER BY 
            managers.employee_id;
        

        4.7.447 - 2025-08-15 13:09:22 +0300 MSK

        Find Followers Count

        Code

        SELECT 
            Followers.user_id, 
            COUNT(Followers.user_id) AS followers_count
        FROM 
            Followers
        GROUP BY 
            Followers.user_id
        ORDER BY
            Followers.user_id ASC;
        

        4.7.448 - 2025-08-15 13:07:52 +0300 MSK

        Find Followers Count

        Code

        SELECT
            followers1.user_id,
            COUNT(DISTINCT followers1.follower_id) AS "followers_count"
        FROM
            Followers followers1
        LEFT JOIN
            Followers followers2
        ON
            followers1.user_id = followers2.user_id
        GROUP BY
            followers1.user_id;
        

        4.7.449 - 2025-08-15 12:54:27 +0300 MSK

        Number Of Rectangles That Can Form The Largest Square

        Code

        class Solution:
            def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
                max_len, res = 0, 0
                for length, width in rectangles:
                    side = min(length, width)
                    if side < max_len:
                        continue
                    elif side == max_len:
                        res += 1
                    else:
                        max_len = side
                        res = 1
                return res
        

        4.7.450 - 2025-08-15 12:49:02 +0300 MSK

        Decode XORed Array

        Code

        class Solution:
            def decode(self, encoded: List[int], first: int) -> List[int]:
                prev_encoded = encoded[0]
                encoded[0] = first
                for i in range(1, len(encoded)):
                    encoded[i], prev_encoded = prev_encoded ^ encoded[i - 1], encoded[i]
                encoded.append(prev_encoded ^ encoded[-1])
                return encoded
        

        4.7.451 - 2025-08-15 12:36:30 +0300 MSK

        Decode XORed Array

        Code

        class Solution:
            def decode(self, encoded: List[int], first: int) -> List[int]:
                prev = first
                for i in range(len(encoded)):
                    prev = encoded[i] ^ prev
                    encoded[i] = prev
                encoded.insert(0, first)
                return encoded
        

        4.7.452 - 2025-08-15 12:28:46 +0300 MSK

        Maximum Units on a Truck

        Code

        class Solution:
            def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
                boxTypes.sort(key=lambda item: item[1])
                res = 0
                while boxTypes and truckSize > 0:
                    boxes, units = boxTypes.pop()
                    count = min(boxes, truckSize)
                    truckSize -= count
                    res += count * units
                return res
        

        4.7.453 - 2025-08-15 12:22:34 +0300 MSK

        Reformat Phone Number

        Code

        class Solution:
            def reformatNumber(self, number: str) -> str:
                digits = []
                for char in number:
                    if char == " " or char == "-":
                        continue
                    digits.append(char)
                res = []
                digits.reverse()
                while len(digits) > 4:
                    res.append("".join((digits.pop(), digits.pop(), digits.pop())))
                length = len(digits)
                if length == 4:
                    res.append("".join((digits.pop(), digits.pop())))
                    res.append("".join((digits.pop(), digits.pop())))
                elif length == 3:
                    res.append("".join((digits.pop(), digits.pop(), digits.pop())))
                elif length == 2:
                    res.append("".join((digits.pop(), digits.pop())))
                return "-".join(res)
        

        4.7.454 - 2025-08-15 11:52:01 +0300 MSK

        Power of Four

        Code

        class Solution:
            def isPowerOfFour(self, n: int) -> bool:
                if n <= 0:
                    return False
                if n & (n - 1) != 0:
                    return False
                while n % 4 == 0:
                    n //= 4
                return n == 1
        

        4.7.455 - 2025-08-15 11:51:01 +0300 MSK

        Power of Four

        Code

        class Solution:
            def isPowerOfFour(self, n: int) -> bool:
                if n <= 0:
                    return False
                while n % 4 == 0:
                    n //= 4
                return n == 1
        

        4.7.456 - 2025-08-14 20:09:09 +0300 MSK

        Largest 3-Same-Digit Number in String

        Code

        class Solution:
            def largestGoodInteger(self, num: str) -> str:
                max_digit = "\0"
                for index in range(len(num) - 2):
                    if num[index] == num[index + 1] == num[index + 2]:
                        max_digit = max(max_digit, num[index])
                if max_digit == "\0":
                    return ""
                return max_digit * 3
        

        4.7.457 - 2025-08-13 17:56:30 +0300 MSK

        Power of Three

        Code

        class Solution:
            def isPowerOfThree(self, n: int) -> bool:
                if n <= 0:
                    return False
                while n % 3 == 0:
                    n //= 3
                return n == 1 
        

        4.7.458 - 2025-08-13 17:55:25 +0300 MSK

        Power of Three

        Code

        class Solution:
            def isPowerOfThree(self, n: int) -> bool:
                if n <= 0:
                    return False
                if n == 1:
                    return True
                while n > 1:
                    if n % 3 != 0:
                        return False
                    n //= 3
                return True
        

        4.7.459 - 2025-08-12 17:49:12 +0300 MSK

        Ways to Express an Integer as Sum of Powers

        Code

        class Solution:
            def numberOfWays(self, n: int, x: int) -> int:
                MOD = 10**9 + 7
                dp = [0] * (n + 1)
                dp[0] = 1
        
                for i in range(1, n + 1):
                    val = i**x
                    if val > n:
                        break
                    for j in range(n, val - 1, -1):
                        dp[j] = (dp[j] + dp[j - val]) % MOD
        
                return dp[n]
        

        4.7.460 - 2025-08-11 18:03:04 +0300 MSK

        Range Product Queries of Powers

        Code

        class Solution:
            def productQueries(self, n: int, queries: List[List[int]]) -> List[int]:
                mod = 10**9 + 7
        
                bins, rep = [], 1
                while n > 0:
                    if n % 2 == 1:
                        bins.append(rep)
                    n //= 2
                    rep *= 2
        
                m = len(bins)
                results = [[0] * m for _ in range(m)]
                for i in range(m):
                    cur = 1
                    for j in range(i, m):
                        cur = cur * bins[j] % mod
                        results[i][j] = cur
        
                ans = []
                for left, right in queries:
                    ans.append(results[left][right])
                return ans
        

        4.7.461 - 2025-08-10 13:14:07 +0300 MSK

        Daily Leads and Partners

        Code

        SELECT 
            DailySales.date_id,
            DailySales.make_name,
            COUNT(DISTINCT DailySales.lead_id) AS unique_leads,
            COUNT(DISTINCT DailySales.partner_id) AS unique_partners
        FROM 
            DailySales
        GROUP BY 
            DailySales.date_id,
            DailySales.make_name;
        

        4.7.462 - 2025-08-10 13:10:37 +0300 MSK

        Invalid Tweets

        Code

        SELECT
            Tweets.tweet_id
        FROM
            Tweets
        WHERE
            LENGTH(Tweets.content) > 15
        

        4.7.463 - 2025-08-10 13:08:24 +0300 MSK

        Goal Parser Interpretation

        Code

        class Solution:
            def interpret(self, command: str) -> str:
                stack = []
                res = []
                for char in command:
                    if char == ")":
                        if stack:
                            res.extend(stack)
                            stack.clear()
                        else:
                            res.append("o")
                    elif char == "G":
                        res.append("G")
                    elif char != "(":
                        stack.append(char)
                return "".join(res)
        

        4.7.464 - 2025-08-10 13:03:22 +0300 MSK

        Maximum Repeating Substring

        Code

        class Solution:
            def maxRepeating(self, sequence: str, word: str) -> int:
                temp, res = word, 0
                while temp in sequence:
                    res += 1
                    temp += word
                return res
        

        4.7.465 - 2025-08-10 12:56:18 +0300 MSK

        Fix Names in a Table

        Code

        SELECT 
            Users.user_id,
            UPPER(LEFT(Users.name, 1)) 
                || LOWER(SUBSTRING(Users.name FROM 2)) AS name
        FROM 
            Users
        ORDER BY 
            Users.user_id;
        

        4.7.466 - 2025-08-10 12:52:07 +0300 MSK

        Average Time of Process per Machine

        Code

        SELECT 
            act1.machine_id, 
            ROUND(AVG(act2.timestamp - act1.timestamp)::decimal, 3) AS processing_time
        FROM
            Activity act1,
            Activity act2
        WHERE 
            act1.machine_id = act2.machine_id
            AND act1.process_id = act2.process_id
            AND act1.activity_type = 'start'
            AND act2.activity_type = 'end'
        GROUP BY 
            act1.machine_id;
        

        4.7.467 - 2025-08-10 12:45:06 +0300 MSK

        Defuse the Bomb

        Code

        class Solution:
            def decrypt(self, code: List[int], k: int) -> List[int]:
                length = len(code)
                result = [0 for _ in range(length)]
                if k == 0:
                    return result
                start, end, window_sum = 1, k + 1, 0
                if k < 0:
                    start = length - (-k)
                    end = length
                for i in range(start, end):
                    window_sum += code[i]
                for i in range(length):
                    result[i] = window_sum
                    window_sum -= code[start % length]
                    window_sum += code[end % length]
                    start += 1
                    end += 1
                return result
        

        4.7.468 - 2025-08-10 12:15:52 +0300 MSK

        Get Maximum in Generated Array

        Code

        class Solution:
            def getMaximumGenerated(self, n: int) -> int:
                if n == 0 or n == 1:
                    return n
                nums = [0] * (n + 1)
                nums[1] = 1
                res = 1
                for i in range(2, n + 1):
                    if i % 2 == 0:
                        val = nums[i // 2]
                    else:
                        val = nums[i // 2] + nums[(i // 2) + 1]
                    nums[i] = val
                    res = max(res, val)
                return res
        

        4.7.469 - 2025-08-10 11:45:24 +0300 MSK

        Check Array Formation Through Concatenation

        Code

        class Solution:
            def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
                num_to_piece = {}
                for i, nums in enumerate(pieces):
                    for num in nums:
                        num_to_piece[num] = i
                i = 0
                length = len(arr)
                while i < length:
                    num1 = arr[i]
                    if num1 not in num_to_piece:
                        return False
                    piece = pieces[num_to_piece[num1]]
                    for j, num2 in enumerate(piece):
                        if i + j >= length:
                            return False
                        num1 = arr[i + j]
                        if num1 != num2:
                            return False
                    i += len(piece)
                return True
        

        4.7.470 - 2025-08-10 11:25:09 +0300 MSK

        Sort Array by Increasing Frequency

        Code

        class Solution:
            def frequencySort(self, nums: List[int]) -> List[int]:
                freqs = collections.defaultdict(int)
                for num in nums:
                    freqs[num] += 1
                nums.sort(key=lambda val: (freqs[val], -val))
                return nums
        

        4.7.471 - 2025-08-10 11:14:30 +0300 MSK

        Percentage of Users Attended a Contest

        Code

        WITH total_users AS (
            SELECT 
                COUNT(DISTINCT user_id) AS total_count
            FROM 
                Users
        )
        SELECT 
            Register.contest_id,
            ROUND(
                COUNT(DISTINCT Register.user_id) * 100.0 / total_users.total_count,
                2
            ) AS percentage
        FROM
            Register
        CROSS JOIN 
            total_users
        GROUP BY 
            Register.contest_id, 
            total_users.total_count
        ORDER BY 
            percentage DESC, 
            Register.contest_id;
        

        4.7.472 - 2025-08-10 11:02:20 +0300 MSK

        Slowest Key

        Code

        class Solution:
            def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
                max_key, max_dur = keysPressed[0], releaseTimes[0]
                for i, num in enumerate(releaseTimes[1:], 1):
                    dur = num - releaseTimes[i - 1]
                    cur_key = keysPressed[i]
                    if dur > max_dur or (dur == max_dur and cur_key > max_key):
                        max_dur = dur
                        max_key = cur_key
                return max_key
        

        4.7.473 - 2025-08-10 10:27:29 +0300 MSK

        Reordered Power of 2

        Code

        class Solution:
            def reorderedPowerOf2(self, n: int) -> bool:
                if n > 0 and n & (n - 1) == 0:
                    return True
                def count_digits(num: int, out: list[int]) -> None:
                    while num > 0:
                        out.append(num % 10)
                        num //= 10
                    out.sort()
                target = []
                count_digits(n, target)
                cur = []
                for i in range(31):
                    cur.clear()
                    count_digits(1 << i, cur)
                    if cur == target:
                        return True
                return False
        

        4.7.474 - 2025-08-09 16:43:21 +0300 MSK

        Mean of Array After Removing Some Elements

        Code

        class Solution:
            def trimMean(self, arr: List[int]) -> float:
                arr.sort()
                length = len(arr)
                interval = length // 20
                res = sum(arr[interval:length - interval])
                res = (res / (length - interval * 2))
                return res
        

        4.7.475 - 2025-08-09 16:34:28 +0300 MSK

        Crawler Log Folder

        Code

        class Solution:
            def minOperations(self, logs: List[str]) -> int:
                depth = 0
                for op in logs:
                    if op == "../":
                        depth = max(depth - 1, 0)
                    elif op == "./":
                        pass
                    else:
                        depth += 1
                return depth
        

        4.7.476 - 2025-08-09 16:31:49 +0300 MSK

        Rearrange Spaces Between Words

        Code

        class Solution:
            def reorderSpaces(self, text: str) -> str:
                res = []
                cur_word = []
                space_count = 0
                for char in text:
                    if char == " ":
                        space_count += 1
                        if cur_word:
                            res.append("".join(cur_word))
                            cur_word.clear()
                    else:
                        cur_word.append(char)
                if cur_word:
                    res.append("".join(cur_word))
                words = len(res) - 1
                if words == 0:
                    join_str = ""
                    rem_str = " " * space_count
                else:
                    join_str = " " * (space_count // words) 
                    rem_str = " " * (space_count % words)
                return "".join((join_str.join(res), rem_str))
        

        4.7.477 - 2025-08-09 16:17:16 +0300 MSK

        Sum of All Odd Length Subarrays

        Code

        class Solution:
            def sumOddLengthSubarrays(self, arr: List[int]) -> int:
                length = len(arr)
                answer = 0
                for i, num in enumerate(arr):
                    left, right = i, length - i - 1
                    odd_left, odd_right = (left // 2) + 1, (right // 2) + 1
                    even_left, even_right = (left + 1) // 2, (right + 1) // 2
                    sub_count = (odd_left * odd_right) + (even_left * even_right)
                    answer += num * sub_count
                return answer
        

        4.7.478 - 2025-08-09 15:53:09 +0300 MSK

        Sum of All Odd Length Subarrays

        Code

        class Solution:
            def sumOddLengthSubarrays(self, arr: List[int]) -> int:
                res = 0
                for i in range(len(arr)):
                    cur_sum = 0
                    for j in range(i, len(arr)):
                        cur_sum += arr[j]
                        if (j - i + 1) % 2 != 0:
                            res += cur_sum
                return res
        

        4.7.479 - 2025-08-09 11:14:40 +0300 MSK

        Power of Two

        Code

        class Solution:
            def isPowerOfTwo(self, n: int) -> bool:
                return n > 0 and (n & (n - 1)) == 0
        

        4.7.480 - 2025-08-08 18:19:33 +0300 MSK

        Soup Servings

        Code

        class Solution:
            def soupServings(self, n: int) -> float:
                m = ceil(n / 25)
                dp = collections.defaultdict(dict)
        
                def calculate_dp(i: int, j: int) -> float:
                    if i <= 0 and j <= 0:
                        return 0.5
                    if i <= 0:
                        return 1.0
                    if j <= 0:
                        return 0.0
                    if i in dp and j in dp[i]:
                        return dp[i][j]
        
                    dp[i][j] = (
                        calculate_dp(i - 4, j)
                        + calculate_dp(i - 3, j - 1)
                        + calculate_dp(i - 2, j - 2)
                        + calculate_dp(i - 1, j - 3)
                    ) / 4.0
                    return dp[i][j]
        
                for k in range(1, m + 1):
                    if calculate_dp(k, k) > 1 - 1e-5:
                        return 1.0
                return calculate_dp(m, m)
        

        4.7.481 - 2025-08-07 17:57:34 +0300 MSK

        Bank Account Summary II

        Code

        SELECT
            Users.name AS "NAME",
            SUM(Transactions.amount) AS "BALANCE"
        FROM
            Users
        LEFT JOIN
            Transactions
        ON
            Users.account = Transactions.account
        GROUP BY
            Users.account, Users.name
        HAVING
            SUM(Transactions.amount) > 10000
        

        4.7.482 - 2025-08-07 17:15:08 +0300 MSK

        Find the Maximum Number of Fruits Collected

        Code

        class Solution:
            def maxCollectedFruits(self, fruits):
                n = len(fruits)
                ans = sum(fruits[i][i] for i in range(n))
        
                def dp():
                    prev = [float("-inf")] * n
                    curr = [float("-inf")] * n
                    prev[n - 1] = fruits[0][n - 1]
                    for i in range(1, n - 1):
                        for j in range(max(n - 1 - i, i + 1), n):
                            best = prev[j]
                            if j - 1 >= 0:
                                best = max(best, prev[j - 1])
                            if j + 1 < n:
                                best = max(best, prev[j + 1])
                            curr[j] = best + fruits[i][j]
                        prev, curr = curr, prev
                    return prev[n - 1]
        
                ans += dp()
        
                for i in range(n):
                    for j in range(i):
                        fruits[i][j], fruits[j][i] = fruits[j][i], fruits[i][j]
        
                ans += dp()
                return ans
        

        4.7.483 - 2025-08-06 19:26:47 +0300 MSK

        Customer Who Visited but Did Not Make Any Transactions

        Code

        SELECT
            Visits.customer_id,
            COUNT(Visits.visit_id) AS "count_no_trans"
        FROM
            Visits
        LEFT JOIN
            Transactions
        ON
            Visits.visit_id = Transactions.visit_id
        WHERE
            Transactions.visit_id IS NULL
        GROUP BY
            Visits.customer_id
        

        4.7.484 - 2025-08-06 16:17:09 +0300 MSK

        Fruits Into Baskets III

        Code

        class Solution:
            def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int:
                length = len(baskets)
                section_length = int(math.sqrt(length))
                sections = (length + section_length - 1) // section_length
                count = 0
                sections_max = [0] * sections
                for i in range(length):
                    section = i // section_length
                    sections_max[section] = max(sections_max[section], baskets[i])
                for fruit in fruits:
                    unset = 1
                    for section in range(sections):
                        if sections_max[section] < fruit:
                            continue
                        choose = 0
                        sections_max[section] = 0
                        for i in range(section_length):
                            pos = section * section_length + i
                            if pos < length and baskets[pos] >= fruit and not choose:
                                baskets[pos] = 0
                                choose = 1
                            if pos < length:
                                sections_max[section] = max(sections_max[section], baskets[pos])
                        unset = 0
                        break
                    count += unset
                return count
        

        4.7.485 - 2025-08-05 20:11:10 +0300 MSK

        Fruits Into Baskets II

        Code

        class Solution:
            def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int:
                count = 0
                length = len(baskets)
                for fruit in fruits:
                    unset = 1
                    for i in range(length):
                        if fruit <= baskets[i]:
                            baskets[i] = 0
                            unset = 0
                            break
                    count += unset
                return count
        

        4.7.486 - 2025-08-04 19:06:02 +0300 MSK

        Fruit Into Baskets

        Code

        class Solution:
            def totalFruit(self, fruits: list[int]) -> int:
                start = 0
                max_len = 0
                fruit_count = defaultdict(int)
        
                for end in range(len(fruits)):
                    fruit_count[fruits[end]] += 1
        
                    while len(fruit_count) > 2:
                        fruit_count[fruits[start]] -= 1
                        if fruit_count[fruits[start]] == 0:
                            del fruit_count[fruits[start]]
                        start += 1
        
                    max_len = max(max_len, end - start + 1)
        
                return max_len
        

        4.7.487 - 2025-08-03 16:36:16 +0300 MSK

        Replace All ?’s to Avoid Consecutive Repeating Characters

        Code

        class Solution:
            def modifyString(self, s: str) -> str:
                res = list(s)
                length = len(s)
        
                for i in range(length):
                    char = res[i]
                    if char != "?":
                        continue
                    for char_ascii in string.ascii_lowercase:
                        if (
                            (i > 0 and res[i - 1] == char_ascii) 
                            or (i < length - 1 and res[i + 1] == char_ascii)
                        ):
                            continue
                        res[i] = char_ascii
                        break
                return "".join(res)
        

        4.7.488 - 2025-08-03 16:21:01 +0300 MSK

        Matrix Diagonal Sum

        Code

        class Solution:
            def diagonalSum(self, mat: List[List[int]]) -> int:
                length = len(mat)
                res = 0
                for i in range(length):
                    row1, col1 = i, i
                    row2, col2 = i, length - i - 1
                    res += mat[row1][col1]
                    if row2 != row1 or col2 != col1:
                        res += mat[row2][col2]
                return res
        

        4.7.489 - 2025-08-03 16:03:54 +0300 MSK

        Detect Pattern of Length M Repeated K or More Times

        Code

        class Solution:
            def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
                length = len(arr)
                if length < m * k:
                    return False
                for i in range(length - m + 1):
                    cur_pat = arr[i:i+m]
                    count = 1
                    for j in range(i + m, length, m):
                        if arr[j:j+m] == cur_pat:
                            count += 1
                        else:
                            break
                    if count >= k:
                        return True
                return False
        

        4.7.490 - 2025-08-03 15:13:16 +0300 MSK

        Most Visited Sector in a Circular Track

        Code

        class Solution:
            def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
                start_sector, end_sector = rounds[0], rounds[-1]
        
                if start_sector <= end_sector:
                    return tuple(range(start_sector, end_sector + 1))
                    
                return tuple(
                    itertools.chain(
                        range(1, end_sector + 1),
                        range(start_sector, n + 1)
                    )
                )
        

        4.7.491 - 2025-08-03 15:01:18 +0300 MSK

        Thousand Separator

        Code

        class Solution:
            def thousandSeparator(self, n: int) -> str:
                if n < 1000:
                    return str(n)
                res = []
                count = 0
                while n > 0:
                    res.append(str(n % 10))
                    count += 1
                    n //= 10
                    if count % 3 == 0 and n > 0:
                        res.append(".")
                res.reverse()
                return "".join(res)
        

        4.7.492 - 2025-08-03 14:57:57 +0300 MSK

        Three Consecutive Odds

        Code

        class Solution:
            def threeConsecutiveOdds(self, arr: List[int]) -> bool:
                count = 0
                for num in arr:
                    if num % 2 == 0:
                        count = 0
                    else:
                        count += 1
                    if count == 3:
                        return True
                return False
        

        4.7.493 - 2025-08-03 14:56:16 +0300 MSK

        Kth Missing Positive Number

        Code

        class Solution:
            def findKthPositive(self, arr: List[int], k: int) -> int:
                prev = 0
                for num in arr:
                    diff = num - prev - 1
                    if k > diff:
                        k -= diff
                    else:
                        return prev + k
                    prev = num
                return prev + k
        

        4.7.494 - 2025-08-03 14:39:49 +0300 MSK

        Shuffle String

        Code

        class Solution:
            def restoreString(self, s: str, indices: List[int]) -> str:
                res = [None] * len(s)
                for i, char in zip(indices, s):
                    res[i] = char
                return "".join(res)
        

        4.7.495 - 2025-08-03 14:36:46 +0300 MSK

        Patients With a Condition

        Code

        SELECT
            Patients.patient_id,
            Patients.patient_name,
            Patients.conditions
        FROM
            Patients
        WHERE
            Patients.conditions ~ '(^|\s)DIAB1'
        

        4.7.496 - 2025-08-03 14:33:50 +0300 MSK

        Water Bottles

        Code

        class Solution:
            def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
                res = 0
                empty = 0
                while numBottles > 0:
                    res += numBottles
                    empty += numBottles
                    numBottles = empty // numExchange
                    empty %= numExchange
                return res
        

        4.7.497 - 2025-08-03 14:29:35 +0300 MSK

        Find Users With Valid E-Mails

        Code

        SELECT 
            *
        FROM 
            Users
        WHERE 
            Users.mail ~ '^[a-zA-Z][a-zA-Z0-9\.\-_]*@leetcode\.com$';
        

        4.7.498 - 2025-08-03 14:27:36 +0300 MSK

        Reformat Date

        Code

        class Solution:
            def reformatDate(self, date: str) -> str:
                day_str, mnth_str, year_str = date.split()
                if len(day_str) == 3:
                    day = int(day_str[0:1])
                else:
                    day = int(day_str[0:2])
                mnth = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].index(mnth_str) + 1
                year = int(year_str)
                return f"{year}-{mnth:02}-{day:02}"
        

        4.7.499 - 2025-08-03 14:18:22 +0300 MSK

        Can Make Arithmetic Progression From Sequence

        Code

        class Solution:
            def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
                arr.sort()
                diff = abs(arr[0] - arr[1])
                for i in range(1, len(arr) - 1):
                    if abs(arr[i] - arr[i+1]) != diff:
                        return False
                return True
        

        4.7.500 - 2025-08-03 14:14:27 +0300 MSK

        Group Sold Products By The Date

        Code

        SELECT 
            Activities.sell_date, 
            COUNT(
                DISTINCT (Activities.product, Activities.sell_date)
            ) AS num_sold, 
            STRING_AGG(
                DISTINCT Activities.product, ',' ORDER BY product
            ) AS products
        FROM 
            Activities
        GROUP BY 
            Activities.sell_date
        ORDER BY 
            Activities.sell_date;
        

        4.7.501 - 2025-08-03 13:56:55 +0300 MSK

        Final Prices With a Special Discount in a Shop

        Code

        class Solution:
            def finalPrices(self, prices: List[int]) -> List[int]:
                stack = deque()
                for i in range(len(prices)):
                    price = prices[i]
                    while True:
                        if not stack:
                            break
                        last_i, last_price = stack[-1]
                        if last_price >= price:
                            prices[last_i] -= price
                            stack.pop()
                        else:
                            break
                    stack.append((i, price))
                return prices
        

        4.7.502 - 2025-08-03 13:42:44 +0300 MSK

        Shuffle the Array

        Code

        class Solution:
            def shuffle(self, nums: List[int], n: int) -> List[int]:
                res = []
                for j in range(n, 2 * n):
                    res.extend((nums[j - n], nums[j]))
                return res
        

        4.7.503 - 2025-08-03 13:35:23 +0300 MSK

        Make Two Arrays Equal by Reversing Subarrays

        Code

        class Solution:
            def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
                freqs = defaultdict(int)
                length = len(target)
                if length != len(arr):
                    return False
                for i in range(length):
                    freqs[target[i]] += 1
                    freqs[arr[i]] -= 1
                for count in freqs.values():
                    if count != 0:
                        return False
                return True
        

        4.7.504 - 2025-08-03 13:30:55 +0300 MSK

        Check If a Word Occurs As a Prefix of Any Word in a Sentence

        Code

        class Solution:
            def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
                for i, word in enumerate(sentence.split()):
                    if word.startswith(searchWord):
                        return i + 1
                return -1
        

        4.7.505 - 2025-08-03 13:25:11 +0300 MSK

        Consecutive Characters

        Code

        class Solution:
            def maxPower(self, s: str) -> int:
                prev = s[0]
                count = 1
                max_count= 1
                for char in s[1:]:
                    if char == prev:
                        count += 1
                        max_count = max(max_count, count)
                    else:
                        count = 1
                        prev = char
                return max_count
        

        4.7.506 - 2025-08-03 13:22:53 +0300 MSK

        Check If All 1’s Are at Least Length K Places Away

        Code

        class Solution:
            def kLengthApart(self, nums: List[int], k: int) -> bool:
                prev = -k - 1
                for i, num in enumerate(nums):
                    if num == 0:
                        continue
                    if i - prev - 1 >= k:
                        prev = i
                    else:
                        return False
                return True
        

        4.7.507 - 2025-08-03 13:19:10 +0300 MSK

        Reformat The String

        Code

        class Solution:
            def reformat(self, s: str) -> str:
                res, digits, al = [""], [], []
                for char in s:
                    if char.isalpha():
                        al.append(char)
                    else:
                        digits.append(char)
                    while digits and al:
                        res.extend((digits.pop(), al.pop()))
                if digits:
                    res.append(digits.pop())
                elif al:
                    res[0] = al.pop()
                if digits or al:
                    return ""
                return "".join(res)
        

        4.7.508 - 2025-08-03 11:38:37 +0300 MSK

        Minimum Value to Get Positive Step by Step Sum

        Code

        class Solution:
            def minStartValue(self, nums: List[int]) -> int:
                min_sum = float('inf')
                cur_sum = 0
                for num in nums:
                    cur_sum += num
                    min_sum = min(min_sum, cur_sum)
                return max(1 - min_sum, 1)
        

        4.7.509 - 2025-08-03 10:42:15 +0300 MSK

        String Matching in an Array

        Code

        class Solution:
        
            class TrieNode:
                def __init__(self):
                    # Tracks how many times this substring appears in the Trie.
                    self.frequency = 0
                    # Maps characters to their respective child nodes.
                    self.child_nodes = {}
        
            def stringMatching(self, words: List[str]) -> List[str]:
                matching_words = []
                root = self.TrieNode()  # Initialize the root of the Trie.
        
                # Insert all suffixes of each word into the Trie.
                for word in words:
                    for start_index in range(len(word)):
                        # Insert each suffix starting from index start_index.
                        self._insert_word(root, word[start_index:])
        
                # Check each word to see if it exists as a substring in the Trie.
                for word in words:
                    if self._is_substring(root, word):
                        matching_words.append(word)
        
                return matching_words
        
            def _insert_word(self, root: "TrieNode", word: str) -> None:
                current_node = root
                for char in word:
                    if char not in current_node.child_nodes:
                        # Create a new node if the character does not exist.
                        current_node.child_nodes[char] = self.TrieNode()
                    current_node = current_node.child_nodes[char]
                    current_node.frequency += 1  # Increment the frequency of the node.
        
            def _is_substring(self, root: "TrieNode", word: str) -> bool:
                current_node = root
                for char in word:
                    # Traverse the Trie following the characters of the word.
                    current_node = current_node.child_nodes[char]
                # A word is a substring if its frequency in the Trie is greater than 1.
                return current_node.frequency > 1
        

        4.7.510 - 2025-08-03 10:26:28 +0300 MSK

        Maximum Fruits Harvested After at Most K Steps

        Code

        class Solution:
            def maxTotalFruits(
                self, fruits: List[List[int]], startPos: int, k: int
            ) -> int:
                n = len(fruits)
                sum_ = [0] * (n + 1)
                indices = [0] * n
        
                for i in range(n):
                    sum_[i + 1] = sum_[i] + fruits[i][1]
                    indices[i] = fruits[i][0]
        
                ans = 0
                for x in range(k // 2 + 1):
                    # move left x steps, then right (k - 2x) steps
                    y = k - 2 * x
                    left = startPos - x
                    right = startPos + y
                    start = bisect_left(indices, left)
                    end = bisect_right(indices, right)
                    ans = max(ans, sum_[end] - sum_[start])
        
                    # move right x steps, then left (k - 2x) steps
                    y = k - 2 * x
                    left = startPos - y
                    right = startPos + x
                    start = bisect_left(indices, left)
                    end = bisect_right(indices, right)
                    ans = max(ans, sum_[end] - sum_[start])
        
                return ans
        

        4.7.511 - 2025-08-02 20:09:46 +0300 MSK

        Top Travellers

        Code

        SELECT
            Users.name, 
            COALESCE(SUM(Rides.distance), 0) AS "travelled_distance"
        FROM
            Users
        LEFT JOIN
            Rides
        ON
            Users.id = Rides.user_id
        GROUP BY
            Users.id, Users.name
        ORDER BY
            travelled_distance DESC,
            Users.name ASC
        

        4.7.512 - 2025-08-02 20:03:30 +0300 MSK

        Minimum Subsequence in Non-Increasing Order

        Code

        class Solution:
            def minSubsequence(self, nums: List[int]) -> List[int]:
                max_sum = sum(nums)
                nums.sort(reverse=True)
                cur_sum = 0
                res = []
                for num in nums:
                    cur_sum += num
                    res.append(num)
                    if cur_sum > max_sum - cur_sum:
                        break
                return res
        

        4.7.513 - 2025-08-02 19:58:48 +0300 MSK

        Count Largest Group

        Code

        class Solution:
            def countLargestGroup(self, n: int) -> int:
                freqs = defaultdict(int)
                def count(num: int) -> int:
                    res = 0
                    while num > 0:
                        res += num % 10
                        num //= 10
                    return res
                max_freq = 0
                for i in range(1, n + 1):
                    group = count(i)
                    freq = freqs[group] + 1
                    freqs[group] = freq
                    if freq > max_freq:
                        max_freq = freq
                res = 0
                for freq in freqs.values():
                    if freq == max_freq:
                        res += 1
                return res
        

        4.7.514 - 2025-08-02 19:54:21 +0300 MSK

        Find Lucky Integer in an Array

        Code

        class Solution:
            def findLucky(self, arr: List[int]) -> int:
                freqs = defaultdict(int)
                for num in arr:
                    freqs[num] += 1
                max_num = -1
                for num, freq in freqs.items():
                    if num == freq:
                        max_num = max(max_num, num)
                return max_num
        

        4.7.515 - 2025-08-02 19:50:44 +0300 MSK

        Create Target Array in the Given Order

        Code

        class Solution:
            def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
                res = []
                for i, num in zip(index, nums):
                    res.insert(i, num)
                return res
        

        4.7.516 - 2025-08-02 19:45:12 +0300 MSK

        Lucky Numbers in a Matrix

        Code

        class Solution:
            def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
                rows = len(matrix)
                cols = len(matrix[0])
                min_row = float("-inf")
                max_col = float("inf")
                for row in range(rows):
                    min_row = max(min_row, min(matrix[row]))
                for col in range(cols):
                    cur_max_col = float("-inf")
                    for row in range(rows):
                        cur_max_col = max(cur_max_col, matrix[row][col])
                    max_col = min(max_col, cur_max_col)
                if min_row == max_col:
                    return [min_row]
                return []
        

        4.7.517 - 2025-08-02 19:36:06 +0300 MSK

        Lucky Numbers in a Matrix

        Code

        class Solution:
            def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
                rows = len(matrix)
                cols = len(matrix[0])
                min_row = [None] * rows
                max_col = [None] * cols
                for row in range(rows):
                    min_row[row] = min(matrix[row])
                for col in range(cols):
                    num_max = float("-inf")
                    for row in range(rows):
                        num = matrix[row][col]
                        if num > num_max:
                            num_max = num
                    max_col[col] = num_max
                res = []
                for row in range(rows):
                    for col in range(cols):
                        num = matrix[row][col]
                        if num == min_row[row] and num == max_col[col]:
                            res.append(num)
                return res
        

        4.7.518 - 2025-08-02 19:28:39 +0300 MSK

        Replace Employee ID With The Unique Identifier

        Code

        SELECT
            EmployeeUNI.unique_id, Employees.name
        FROM
            Employees
        LEFT JOIN
            EmployeeUNI
        ON
            Employees.id = EmployeeUNI.id
        

        4.7.519 - 2025-08-02 19:24:42 +0300 MSK

        Generate a String With Characters That Have Odd Counts

        Code

        class Solution:
            def generateTheString(self, n: int) -> str:
                if n % 2 == 0:
                    return ("a" * (n - 1)) + "b"
                return "a" * n
        

        4.7.520 - 2025-08-02 19:22:20 +0300 MSK

        Increasing Decreasing String

        Code

        class Solution:
            def sortString(self, s: str) -> str:
                freqs = defaultdict(int)
                for char in s:
                    freqs[char] += 1
                keys = list(freqs.keys())
                keys.sort(key = ord)
                length = len(keys)
                res = []
                while freqs:
                    for i in itertools.chain(range(length), reversed(range(length))):
                        key = keys[i]
                        if key not in freqs:
                            continue
                        res.append(key)
                        freqs[key] -= 1
                        if freqs[key] == 0:
                            freqs.pop(key)
                return "".join(res)
        

        4.7.521 - 2025-08-02 19:12:42 +0300 MSK

        How Many Numbers Are Smaller Than the Current Number

        Code

        class Solution:
            def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
                num_to_count = {}
                for i, num in enumerate(sorted(nums)):
                    if num not in num_to_count:
                        num_to_count[num] = i
                for i in range(len(nums)):
                    nums[i] = num_to_count[nums[i]]
                return nums
        

        4.7.522 - 2025-08-02 19:08:24 +0300 MSK

        Number of Days Between Two Dates

        Code

        class Solution:
            def daysBetweenDates(self, date1: str, date2: str) -> int:
                year1, month1, day1 = map(int, date1.split('-'))
                year2, month2, day2 = map(int, date2.split('-'))
                date1 = datetime.date(year1, month1, day1)
                date2 = datetime.date(year2, month2, day2) 
                return abs((date2 - date1).days)
        

        4.7.523 - 2025-08-02 18:59:52 +0300 MSK

        Check If N and Its Double Exist

        Code

        class Solution:
            def checkIfExist(self, arr: List[int]) -> bool:
                enc = set()
                for num in arr:
                    if num == 0 and 0 in enc:
                        return True
                    if num % 2 == 0 and num // 2 in enc:
                        return True
                    if num * 2 in enc:
                        return True
                    enc.add(num)
                return False
        

        4.7.524 - 2025-08-02 18:49:48 +0300 MSK

        Remove Palindromic Subsequences

        Code

        class Solution:
            def removePalindromeSub(self, s: str) -> int:
                if s == s[::-1]:
                    return 1
                return 2
        

        4.7.525 - 2025-08-02 18:45:57 +0300 MSK

        Rank Transform of an Array

        Code

        class Solution:
            def arrayRankTransform(self, arr: List[int]) -> List[int]:
                num_to_rank = defaultdict(int)
                nums = sorted(set(arr))
                for rank, num in enumerate(nums, 1):
                    num_to_rank[num] = rank
                for i in range(len(arr)):
                    arr[i] = num_to_rank[arr[i]]
                return arr
        

        4.7.526 - 2025-08-02 18:40:13 +0300 MSK

        Rank Transform of an Array

        Code

        class Solution:
            def arrayRankTransform(self, arr: List[int]) -> List[int]:
                ind = defaultdict(list)
                for i, num in enumerate(arr):
                    ind[num].append(i)
                for rank, num in enumerate(sorted(ind.keys()), 1):
                    for i in ind[num]:
                        arr[i] = rank
                return arr
        

        4.7.527 - 2025-08-02 18:33:48 +0300 MSK

        List the Products Ordered in a Period

        Code

        SELECT 
            Products.product_name, SUM(Orders.unit) as "unit"
        FROM 
            Products
        JOIN 
            Orders
        ON 
            Orders.product_id = Products.product_id
        WHERE 
            Orders.order_date BETWEEN '2020-02-01' AND '2020-02-29'
        GROUP BY 
            Products.product_name
        HAVING 
            SUM(Orders.unit) >= 100;
        

        4.7.528 - 2025-08-02 18:22:51 +0300 MSK

        Maximum 69 Number

        Code

        class Solution:
            def maximum69Number(self, num: int) -> int:
                digits = []
                while num > 0:
                    digits.append(num % 10)
                    num //= 10
                digits.reverse()
                res = 0
                enc = False
                length = len(digits)
                for i, digit in enumerate(digits):
                    if digit == 6 and not enc:
                        digit = 9
                        enc = True
                    res += (10 ** (length - i - 1)) * digit
                return res
        

        4.7.529 - 2025-08-02 18:14:37 +0300 MSK

        Convert Integer to the Sum of Two No-Zero Integers

        Code

        class Solution:
            def getNoZeroIntegers(self, n: int) -> List[int]:
                if n <= 10:
                    return [1, n - 1]
                def check(num: int) -> bool:
                    while num > 0:
                        if num % 10 == 0:
                            return False
                        num //= 10
                    return True
                for i in range(1, (n + 1) // 2):
                    num1, num2 = i, n - i
                    if check(num1) and check(num2):
                        return [num1, num2]
                raise Exception
        

        4.7.530 - 2025-08-02 18:07:54 +0300 MSK

        Decompress Run-Length Encoded List

        Code

        class Solution:
            def decompressRLElist(self, nums: List[int]) -> List[int]:
                res = []
                i = 0
                length = len(nums)
                while i < length:
                    freq, val = nums[i], nums[i + 1]
                    i += 2
                    res.extend((val, ) * freq)
                return res
        

        4.7.531 - 2025-08-02 18:04:04 +0300 MSK

        Decrypt String from Alphabet to Integer Mapping

        Code

        class Solution:
            def freqAlphabets(self, s: str) -> str:
                res = []
                length = len(s)
                i = 0
                while i < length:
                    if i + 2 <  length and s[i + 2] == "#":
                        res.append(chr(int(s[i:i+2]) + 97 - 1))
                        i += 3
                    else:
                        res.append(chr(int(s[i]) + 97 - 1))
                        i += 1
                return "".join(res)
        

        4.7.532 - 2025-08-02 17:59:03 +0300 MSK

        Find N Unique Integers Sum up to Zero

        Code

        class Solution:
            def sumZero(self, n: int) -> List[int]:
                if n == 1:
                    return [0]
                res = []
                if n % 2 != 0:
                    res.append(0)
                    n -= 1
                for i in range(1, (n // 2) + 1):
                    res.extend((i, -i))
                return res
        

        4.7.533 - 2025-08-02 17:54:14 +0300 MSK

        Replace Elements with Greatest Element on Right Side

        Code

        class Solution:
            def replaceElements(self, arr: List[int]) -> List[int]:
                greatest = -1
                for i in reversed(range(len(arr))):
                    current = arr[i]
                    arr[i] = greatest
                    if current > greatest:
                        greatest = current
                return arr
        

        4.7.534 - 2025-08-02 17:28:54 +0300 MSK

        Find Numbers with Even Number of Digits

        Code

        class Solution:
            def findNumbers(self, nums: List[int]) -> int:
                def count(num: int) -> int:
                    res = 0
                    while num:
                        res += 1
                        num //= 10
                    return res
                res = 0
                for num in nums:
                    if count(num) % 2 == 0:
                        res += 1
                return res
        

        4.7.535 - 2025-08-02 17:26:28 +0300 MSK

        Convert Binary Number in a Linked List to Integer

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def getDecimalValue(self, head: Optional[ListNode]) -> int:
                res = 0
                while head:
                    res <<= 1
                    res |= head.val
                    head = head.next
                return res
        

        4.7.536 - 2025-08-02 17:24:46 +0300 MSK

        Students and Examinations

        Code

        SELECT
            Students.student_id, 
            Students.student_name,
            Subjects.subject_name,
            COUNT(Examinations.subject_name) as "attended_exams"
        FROM
            Students
        CROSS JOIN
            Subjects
        LEFT JOIN
            Examinations
        ON
            Students.student_id = Examinations.student_id
            AND Subjects.subject_name = Examinations.subject_name
        GROUP BY
            Students.student_id, 
            Students.student_name, 
            Subjects.subject_name
        ORDER BY
            Students.student_id, 
            Subjects.subject_name
        

        4.7.537 - 2025-08-02 17:06:00 +0300 MSK

        Find Winner on a Tic Tac Toe Game

        Code

        class Solution:
            def tictactoe(self, moves: List[List[int]]) -> str:
                cols = [[0] * 3 for _ in range(2)]
                rows = [[0] * 3 for _ in range(2)]
                diags = [[0] * 2 for _ in range(2)]
                players = ["A", "B"]
                for i, (row, col) in enumerate(moves):
                    if i % 2 == 0:
                        player = 0
                    else:
                        player = 1
                    rows[player][row] += 1
                    cols[player][col] += 1
                    if row == col:
                        diags[player][0] += 1
                    if row == 2 - col:
                        diags[player][1] += 1
                for player in range(2):
                    for win in (cols, rows, diags):
                        if 3 in win[player]:
                            return players[player]
                if len(moves) == 9:
                    return "Draw"
                return "Pending"
        

        4.7.538 - 2025-08-02 16:50:59 +0300 MSK

        Shift 2D Grid

        Code

        class Solution:
            def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
                if not grid or not grid[0]:
                    return grid
                
                row_length = len(grid)
                col_length = len(grid[0])
                num_count = row_length * col_length
                k %= num_count
                res = [[0] * col_length for _ in range(row_length)]
                
                for row in range(row_length):
                    for col in range(col_length):
                        flat_mat_index = (row * col_length) + col
                        new_flat_mat_index = (flat_mat_index + k) % num_count
                        new_row = new_flat_mat_index // col_length
                        new_col = new_flat_mat_index % col_length
                        res[new_row][new_col] = grid[row][col]
                return res
        

        4.7.539 - 2025-08-02 16:38:17 +0300 MSK

        Cells with Odd Values in a Matrix

        Code

        class Solution:
            def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
                mat = [[0] * n for _ in range(m)]
                for row, col in indices:
                    for cur_col in range(n):
                        mat[row][cur_col] += 1
                    for cur_row in range(m):
                        mat[cur_row][col] += 1
                count = 0
                for row in range(m):
                    for col in range(n):
                        if mat[row][col] % 2 != 0:
                            count += 1
                return count
        

        4.7.540 - 2025-08-02 16:29:04 +0300 MSK

        Rearranging Fruits

        Code

        class Solution:
            def minCost(self, basket1: List[int], basket2: List[int]) -> int:
                freq = Counter()
                m = float("inf")
                for b1 in basket1:
                    freq[b1] += 1
                    m = min(m, b1)
                for b2 in basket2:
                    freq[b2] -= 1
                    m = min(m, b2)
        
                merge = []
                for k, c in freq.items():
                    if c % 2 != 0:
                        return -1
                    merge.extend([k] * (abs(c) // 2))
        
                if not merge:
                    return 0
                merge.sort()
                return sum(min(2 * m, x) for x in merge[: len(merge) // 2])
        

        4.7.541 - 2025-08-02 16:25:49 +0300 MSK

        Average Selling Price

        Code

        SELECT 
            Prices.product_id,
            CASE
                WHEN 
                    SUM(UnitsSold.units) is null
                THEN 
                    0
                ELSE
                    ROUND(SUM(UnitsSold.units * Prices.price) / SUM(UnitsSold.units)::numeric, 2)
            END AS average_price
        FROM 
            Prices
        LEFT JOIN 
            UnitsSold
        ON 
            UnitsSold.product_id = Prices.product_id 
            AND UnitsSold.purchase_date 
                BETWEEN Prices.start_date AND Prices.end_date
        GROUP BY 
            Prices.product_id;
        

        4.7.542 - 2025-08-02 16:11:25 +0300 MSK

        Check If It Is a Straight Line

        Code

        class Solution:
            def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
                x1, y1 = coordinates[0]
                x2, y2 = coordinates[1]
                for x3, y3 in coordinates[2:]:
                    if (x3 - x1) * (y2 - y1) != (x2 - x1) * (y3 - y1):
                        return False
                return True
        

        4.7.543 - 2025-08-02 16:04:47 +0300 MSK

        Split a String in Balanced Strings

        Code

        class Solution:
            def balancedStringSplit(self, s: str) -> int:
                count_l, count_r = 0, 0
                count = 0
                for char in s:
                    if char == "R":
                        count_r += 1
                    else:
                        count_l += 1
                    if count_l == count_r:
                        count += 1
                return count
                    
        

        4.7.544 - 2025-08-02 15:56:06 +0300 MSK

        Minimum Cost to Move Chips to The Same Position

        Code

        class Solution:
            def minCostToMoveChips(self, position: List[int]) -> int:
                length = len(position)
                odd, even = 0, 0
                for pos in position:
                    if pos % 2 == 0:
                        even += 1
                    else:
                        odd += 1
                return min(odd, even)
        

        4.7.545 - 2025-08-02 15:46:47 +0300 MSK

        Queries Quality and Percentage

        Code

        SELECT 
            query_name,  
            ROUND(SUM(rating * 1.0 / position) / COUNT(*), 2) AS quality,
            ROUND(
                COUNT(CASE WHEN rating < 3 THEN 1 END) * 1.0 / COUNT(*), 
                4
            ) * 100 AS poor_query_percentage
        FROM 
            Queries
        GROUP BY 
            query_name;
        

        4.7.546 - 2025-08-02 15:43:09 +0300 MSK

        Minimum Absolute Difference

        Code

        class Solution:
            def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
                arr.sort()
                min_diff = float("inf")
                res = []
                for i, num in enumerate(arr[:-1]):
                    nxt = arr[i + 1]
                    diff = abs(nxt - num)
                    if diff < min_diff:
                        res.clear()
                        res.append((num, nxt))
                        min_diff = diff
                    elif diff == min_diff:
                        res.append((num, nxt))
                return res
        

        4.7.547 - 2025-08-02 15:41:03 +0300 MSK

        Minimum Absolute Difference

        Code

        class Solution:
            def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
                arr.sort()
                min_diff = float("inf")
                diffs = defaultdict(list)
                for i, num in enumerate(arr[:-1]):
                    nxt = arr[i + 1]
                    diff = abs(nxt - num)
                    diffs[diff].append((num, nxt))
                    min_diff = min(min_diff, diff)
                return diffs[min_diff]
        

        4.7.548 - 2025-08-02 15:39:53 +0300 MSK

        Minimum Absolute Difference

        Code

        class Solution:
            def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
                arr.sort()
                min_diff = float("inf")
                res = []
                for i, num in enumerate(arr[:-1]):
                    nxt = arr[i + 1]
                    diff = abs(nxt - num)
                    min_diff = min(min_diff, diff)
                for i, num in enumerate(arr[:-1]):
                    nxt = arr[i + 1]
                    diff = abs(nxt - num)
                    if diff == min_diff:
                        res.append((num, nxt))
                return res
        

        4.7.549 - 2025-08-02 15:34:16 +0300 MSK

        Maximum Number of Balloons

        Code

        class Solution:
            def maxNumberOfBalloons(self, text: str) -> int:
                freqs = defaultdict(int)
                for char in text:
                    freqs[char] += 1
                res = min(
                    freqs["b"],
                    freqs["a"],
                    freqs["l"] // 2,
                    freqs["o"] // 2,
                    freqs["n"]
                )
                return res
        

        4.7.550 - 2025-08-02 15:27:49 +0300 MSK

        Day of the Week

        Code

        class Solution:
            def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
                return [
                    "Monday", "Tuesday", "Wednesday", 
                    "Thursday", "Friday", "Saturday", 
                    "Sunday"
                ][datetime.date(year, month, day).weekday()]
        

        4.7.551 - 2025-08-02 15:19:46 +0300 MSK

        Distance Between Bus Stops

        Code

        class Solution:
            def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
                length = len(distance)
                forward_dist, back_dist = 0, 0
                forward, back = start, start
                while True:
                    if forward == destination:
                        return forward_dist
                    if back == destination or length + back == destination:
                        return back_dist
                    forward_dist += distance[forward]
                    forward = (forward + 1) % length
                    back_dist += distance[back - 1]
                    back -= 1
                raise Exception
        

        4.7.552 - 2025-08-02 15:01:25 +0300 MSK

        Reformat Department Table

        Code

        SELECT id,
                SUM(
                    CASE 
                        WHEN 
                            month = 'Jan' 
                        THEN 
                            revenue 
                        ELSE 
                            NULL 
                    END
                ) AS Jan_Revenue,
                SUM(
                    CASE 
                        WHEN 
                            month = 'Feb' 
                        THEN 
                            revenue 
                        ELSE 
                            NULL 
                        END
                ) AS Feb_Revenue,
                SUM(
                    CASE 
                        WHEN 
                            month = 'Mar' 
                        THEN 
                            revenue 
                        ELSE 
                            NULL 
                        END
                ) AS Mar_Revenue,
                SUM(
                    CASE 
                        WHEN 
                            month = 'Apr' 
                        THEN 
                            revenue 
                        ELSE 
                            NULL 
                        END
                ) AS Apr_Revenue,
                SUM(
                    CASE 
                        WHEN 
                            month = 'May' 
                        THEN 
                            revenue 
                        ELSE 
                            NULL 
                        END
                ) AS May_Revenue,
                SUM(
                    CASE 
                        WHEN 
                            month = 'Jun' 
                        THEN 
                            revenue 
                        ELSE 
                            NULL 
                        END
                ) AS Jun_Revenue,
                SUM(
                    CASE 
                        WHEN 
                            month = 'Jul'
                        THEN 
                            revenue 
                        ELSE 
                            NULL 
                        END
                ) AS Jul_Revenue,
                SUM(
                    CASE 
                        WHEN 
                            month = 'Aug'
                        THEN 
                            revenue 
                        ELSE 
                            NULL
                        END
                ) AS Aug_Revenue,
                SUM(
                    CASE 
                        WHEN 
                            month = 'Sep' 
                        THEN 
                            revenue 
                        ELSE 
                            NULL 
                        END
                ) AS Sep_Revenue,
                SUM(
                    CASE 
                        WHEN 
                            month = 'Oct' 
                        THEN 
                            revenue 
                        ELSE 
                            NULL 
                    END
                ) AS Oct_Revenue,
                SUM(
                    CASE 
                        WHEN 
                            month = 'Nov' 
                        THEN 
                            revenue 
                        ELSE 
                            NULL 
                    END
                ) AS Nov_Revenue,
                SUM(
                    CASE 
                        WHEN 
                            month = 'Dec' 
                        THEN 
                            revenue 
                        ELSE 
                            NULL 
                    END
                ) AS Dec_Revenue
        FROM 
            Department
        GROUP BY 
            id;
        

        4.7.553 - 2025-08-02 14:54:02 +0300 MSK

        Prime Arrangements

        Code

        class Solution:
            def numPrimeArrangements(self, n: int) -> int:
                prime = [True] * (n + 1)
                prime[0] = prime[1] = False
                for i in range(2, int(n ** 0.5) + 1):
                    if not prime[i]:
                        continue
                    for j in range(i * i, n + 1, i):
                        prime[j] = False
                            
                prime_count = sum(prime)
                mod = 10**9 + 7
                fact_primes = math.factorial(prime_count)
                fact_norm = math.factorial(n - prime_count)
                return (fact_primes * fact_norm) % mod
        
                
        

        4.7.554 - 2025-08-02 14:25:28 +0300 MSK

        Day of the Year

        Code

        class Solution:
            def dayOfYear(self, date: str) -> int:
                year, month, day = map(int, date.split('-'))
                days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
                if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
                    days_in_month[1] = 29
                day_number = sum(days_in_month[:month - 1]) + day
                return day_number
        

        4.7.555 - 2025-08-02 14:21:50 +0300 MSK

        Article Views I

        Code

        SELECT DISTINCT
            views1.author_id as "id"
        FROM
            Views views1
        CROSS JOIN
            Views views2
        WHERE
            views1.author_id = views2.viewer_id
            AND views1.author_id = views2.author_id
        ORDER BY
            views1.author_id ASC
        

        4.7.556 - 2025-08-02 14:15:20 +0300 MSK

        User Activity for the Past 30 Days I

        Code

        SELECT 
            activity_date AS day, 
            COUNT(DISTINCT(user_id)) AS active_users  
        FROM 
            Activity 
        WHERE 
            activity_date 
                BETWEEN '2019-07-27'::DATE - INTERVAL '29 DAYS' 
                AND '2019-07-27'::DATE
        GROUP BY 
            activity_date
        

        4.7.557 - 2025-08-02 14:10:21 +0300 MSK

        Number of Equivalent Domino Pairs

        Code

        class Solution:
            def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
                freqs = [0] * 100
                res = 0
                for num1, num2 in dominoes:
                    if num1 > num2:
                        val = num1 * 10 + num2
                    else:
                        val = num2 * 10 + num1
                    res += freqs[val]
                    freqs[val] += 1
                return res
        

        4.7.558 - 2025-08-02 14:00:42 +0300 MSK

        Print in Order

        Code

        class Foo:
            def __init__(self):
                self._lock1 = threading.Lock()
                self._lock2 = threading.Lock()
                self._lock1.acquire()
                self._lock2.acquire()
        
            def first(self, printFirst: 'Callable[[], None]') -> None:
                printFirst()
                self._lock1.release()
        
        
            def second(self, printSecond: 'Callable[[], None]') -> None:
                with self._lock1:
                    printSecond()
                self._lock2.release()
        
        
            def third(self, printThird: 'Callable[[], None]') -> None:
                with self._lock2:
                    printThird()
        

        4.7.559 - 2025-08-02 13:55:22 +0300 MSK

        Defanging an IP Address

        Code

        class Solution:
            def defangIPaddr(self, address: str) -> str:
                return address.replace(".", "[.]")
        

        4.7.560 - 2025-08-02 13:54:26 +0300 MSK

        Distribute Candies to People

        Code

        class Solution:
            def distributeCandies(self, candies: int, num_people: int) -> List[int]:
                res = [0] * num_people
                i = 0
                while candies > 0:
                    loss = min(i + 1, candies)
                    res[i % num_people] += loss
                    i += 1
                    candies -= loss
                return res
        

        4.7.561 - 2025-08-02 13:48:16 +0300 MSK

        Distribute Candies to People

        Code

        class Solution:
            def distributeCandies(self, candies: int, num_people: int) -> List[int]:
                res = [0] * num_people
                mult = 0
                while candies > 0:
                    for i in range(num_people):
                        target = min((mult * num_people) + (i + 1), candies)
                        if candies > 0: 
                            res[i] += target
                            candies -= target
                        else:
                            break
                    mult += 1
                return res
        

        4.7.562 - 2025-08-02 13:02:23 +0300 MSK

        Duplicate Zeros

        Code

        class Solution:
            def duplicateZeros(self, arr: List[int]) -> None:
                """
                Do not return anything, modify arr in-place instead.
                """
        
                possible_dups = 0
                length_ = len(arr) - 1
        
                for left in range(length_ + 1):
                    if left > length_ - possible_dups:
                        break
                    if arr[left] == 0:
                        if left == length_ - possible_dups:
                            arr[length_] = 0
                            length_ -= 1
                            break
                        possible_dups += 1
        
                last = length_ - possible_dups
                for i in range(last, -1, -1):
                    if arr[i] == 0:
                        arr[i + possible_dups] = 0
                        possible_dups -= 1
                        arr[i + possible_dups] = 0
                    else:
                        arr[i + possible_dups] = arr[i]
        

        4.7.563 - 2025-08-02 12:36:15 +0300 MSK

        Duplicate Zeros

        Code

        class Solution:
            def duplicateZeros(self, arr: List[int]) -> None:
                """
                Do not return anything, modify arr in-place instead.
                """
                queue = deque()
                for i in range(len(arr)):
                    num = arr[i]
                    if queue:
                        arr[i] = queue.popleft()
                        queue.append(num)
                    if num == 0:
                        queue.append(0)
        

        4.7.564 - 2025-08-02 12:22:49 +0300 MSK

        Sales Analysis III

        Code

        SELECT 
            Product.product_id, Product.product_name
        FROM 
            Sales
        JOIN 
            Product 
        ON 
            Product.product_id = Sales.product_id
        GROUP BY 
            Product.product_id, Product.product_name
        HAVING
            MIN(Sales.sale_date) >= '2019-01-01' 
            AND MAX(Sales.sale_date) <= '2019-03-31'
        

        4.7.565 - 2025-08-02 11:12:11 +0300 MSK

        Occurrences After Bigram

        Code

        class Solution:
            def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
                words = text.split()
                length = len(words)
                if length < 3:
                    return []
                res = []
                i = 0
                while i + 2 < length:
                    if words[i] == first and words[i+1] == second:
                        res.append(words[i+2])
                    i += 1
                return res
        

        4.7.566 - 2025-08-02 10:56:41 +0300 MSK

        Project Employees I

        Code

        SELECT 
            project_id,
            ROUND(AVG(experience_years), 2) AS average_years
        FROM 
            Project
        JOIN 
            Employee
        ON 
            Project.employee_id = Employee.employee_id
        GROUP BY 
            project_id
        

        4.7.567 - 2025-08-02 10:53:44 +0300 MSK

        Project Employees I

        Code

        SELECT 
            project_id,
            ROUND(AVG(experience_years), 2) AS average_years
        FROM 
            Project
        JOIN 
            Employee
        ON 
            Project.employee_id = Employee.employee_id
        GROUP BY 
            project_id
        

        4.7.568 - 2025-08-02 10:46:44 +0300 MSK

        Product Sales Analysis I

        Code

        SELECT
            product_name, year, price
        FROM 
            Sales
        LEFT JOIN
            Product
        ON
            Sales.product_id = Product.product_id
        

        4.7.569 - 2025-08-02 10:41:17 +0300 MSK

        Actors and Directors Who Cooperated At Least Three Times

        Code

        SELECT 
            actor_id, director_id
        FROM 
            ActorDirector
        GROUP BY 
            actor_id, director_id
        HAVING 
            COUNT(actor_id) >= 3;
        

        4.7.570 - 2025-08-02 10:38:33 +0300 MSK

        Remove All Adjacent Duplicates In String

        Code

        class Solution:
            def removeDuplicates(self, s: str) -> str:
                stack = []
                for char in s:
                    if stack and char == stack[-1]:
                        stack.pop()
                    else:
                        stack.append(char)
                return "".join(stack)
        

        4.7.571 - 2025-08-02 10:31:09 +0300 MSK

        Last Stone Weight

        Code

        class Solution:
            def lastStoneWeight(self, stones: List[int]) -> int:
                for i, num in enumerate(stones):
                    stones[i] = -num
                heapq.heapify(stones)
                while stones:
                    last = -heapq.heappop(stones)
                    if not stones:
                        return last
                    prev = -heapq.heappop(stones)
                    if last > prev:
                        heapq.heappush(stones, -(last - prev))
                return 0
        

        4.7.572 - 2025-08-02 10:28:21 +0300 MSK

        Last Stone Weight

        Code

        class Solution:
            def lastStoneWeight(self, stones: List[int]) -> int:
                stones.sort()
                while stones:
                    last = stones.pop()
                    if not stones:
                        return last
                    prev = stones[-1]
                    if last == prev:
                        stones.pop()
                    else:
                        stones[-1] = last - prev
                        stones.sort()
                return 0
        

        4.7.573 - 2025-08-02 09:19:39 +0300 MSK

        Valid Boomerang

        Code

        class Solution:
            def isBoomerang(self, points: List[List[int]]) -> bool:
                x1, y1 = points[0]
                x2, y2 = points[1]
                x3, y3 = points[2]
                return (y2 - y1) * (x3 - x2) != (y3 - y2) * (x2 - x1)
        

        4.7.574 - 2025-08-02 09:15:14 +0300 MSK

        Matrix Cells in Distance Order

        Code

        class Solution:
            def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
                res = []
                for row in range(rows):
                    for col in range(cols):
                        res.append((row, col))
                def key(point: tuple[int, int]) -> int:
                    row, col = point
                    return abs(row - rCenter) + abs(col - cCenter)
                res.sort(key=key) 
                return res
        

        4.7.575 - 2025-08-02 09:11:31 +0300 MSK

        Matrix Cells in Distance Order

        Code

        class Solution:
            def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
                res = []
                for row in range(rows):
                    for col in range(cols):
                        dist = abs(row - rCenter) + abs(col - cCenter)
                        res.append((dist, row, col))
                res.sort()
                for i in range(len(res)):
                    res[i] = res[i][1:] 
                return res
        

        4.7.576 - 2025-08-02 09:03:11 +0300 MSK

        Divisor Game

        Code

        class Solution:
            def divisorGame(self, n: int) -> bool:
                return n % 2 == 0
        

        4.7.577 - 2025-08-02 08:55:10 +0300 MSK

        Sum of Root To Leaf Binary Numbers

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
                res = 0
                queue = [(root, 0)]
                while queue:
                    node, parent = queue.pop()
                    if node is None:
                        continue
                    val = (parent << 1) | node.val
                    if not node.left and not node.right:
                        res += val
                    queue.extend(((node.left, val), (node.right, val)))
                return res
        

        4.7.578 - 2025-08-02 08:53:28 +0300 MSK

        Sum of Root To Leaf Binary Numbers

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
                def dfs(node: Optional[TreeNode], parent: int) -> int:
                    if node is None:
                        return 0
                    cur_val = (parent << 1) | node.val
                    if not node.left and not node.right:
                        return cur_val
                    return dfs(node.left, cur_val) + dfs(node.right, cur_val)
                return dfs(root, 0)
        

        4.7.579 - 2025-08-02 08:48:51 +0300 MSK

        Remove Outermost Parentheses

        Code

        class Solution:
            def removeOuterParentheses(self, s: str) -> str:
                res = []
                balance = 0
                start = 0
        
                for i, char in enumerate(s):
                    if char == '(':
                        balance += 1
                    else:
                        balance -= 1
                    if balance == 0:
                        res.append(s[start + 1:i])
                        start = i + 1
                return "".join(res)
        

        4.7.580 - 2025-08-02 08:38:26 +0300 MSK

        Binary Prefix Divisible By 5

        Code

        class Solution:
            def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
                cur = 0
                for i in range(len(nums)):
                    cur <<= 1
                    cur |= nums[i]
                    nums[i] = cur % 5 == 0
                return nums
        

        4.7.581 - 2025-08-02 08:34:40 +0300 MSK

        Partition Array Into Three Parts With Equal Sum

        Code

        class Solution:
            def canThreePartsEqualSum(self, arr: List[int]) -> bool:
                total = sum(arr)
                if total % 3 != 0:
                    return False
                length = len(arr)
                target = total // 3
                cur = 0
                count = 0
                for i, num in enumerate(arr):
                    cur += num
                    if cur == target:
                        cur = 0
                        count += 1
                    if count == 2 and i + 1 < length:
                        return True
                return False
        

        4.7.582 - 2025-08-01 21:34:49 +0300 MSK

        Complement of Base 10 Integer

        Code

        class Solution:
            def bitwiseComplement(self, n: int) -> int:
                if n == 0:
                    return 1
                res, count = 0, 0
                while n > 0:
                    if n & 1 == 0:
                        res += 2 ** count
                    count += 1
                    n >>= 1
                return res
        

        4.7.583 - 2025-08-01 21:23:46 +0300 MSK

        Maximize Sum Of Array After K Negations

        Code

        class Solution:
            def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
                nums.sort()
                for i in range(len(nums)):
                    num = nums[i]
                    if num < 0 and k > 0:
                        nums[i] = -num
                        k -= 1
                    else:
                        break
                if k == 0 or k % 2 == 0:
                    return sum(nums)
                nums.sort()
                nums[0] = -nums[0]
                return sum(nums)
        

        4.7.584 - 2025-08-01 20:49:53 +0300 MSK

        Available Captures for Rook

        Code

        class Solution:
            def numRookCaptures(self, board: List[List[str]]) -> int:
                bishop_row, bishop_col = -1, -1
                length = len(board)
                delta = (
                    (0, 1), (0, -1), (1, 0), (-1, 0)            
                )
                for row in range(length):
                    for col in range(length):
                        if board[row][col] == "R":
                            bishop_row, bishop_col = row, col
                            break
                    if bishop_row != -1:
                        break
                count = 0
                for delta_row, delta_col in delta:
                    row, col = bishop_row, bishop_col
                    while 0 <= row < length and 0 <= col < length:
                        char = board[row][col]
                        if char == "p":
                            count += 1
                            break
                        elif char == "B":
                            break
                        row, col = row + delta_row, col + delta_col
                return count
        

        4.7.585 - 2025-08-01 20:14:01 +0300 MSK

        Cousins in Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
                def dfs(node: Optional[TreeNode], depth: int) -> tuple[int, int]:
                    if node is None:
                        return 0, 0
                    if node.val == x:
                        return depth, 0
                    if node.val == y:
                        return 0, depth
                    depth1_x, depth1_y = dfs(node.left, depth + 1)
                    depth2_x, depth2_y = dfs(node.right, depth + 1)
                    depth1, depth2 = depth1_x or depth2_x, depth1_y or depth2_y
                    if depth1 and depth2 and depth1 == depth + 1:
                        return 0, 0
                    return depth1, depth2
        
                depth1, depth2 = dfs(root, 0)
                return depth1 == depth2 and depth1 > 1
        

        4.7.586 - 2025-08-01 19:32:18 +0300 MSK

        Univalued Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
                queue = [root]
                while queue:
                    node = queue.pop()
                    if node.right and node.val != node.right.val:
                        return False
                    if node.left and node.val != node.left.val:
                        return False
                    if node.left:
                        queue.append(node.left)
                    if node.right:
                        queue.append(node.right)
                return True
        

        4.7.587 - 2025-08-01 19:30:30 +0300 MSK

        Univalued Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
                def dfs(node: Optional[TreeNode]) -> bool:
                    if node is None:
                        return True
                    if node.left and node.val != node.left.val:
                        return False
                    if node.right and node.val != node.right.val:
                        return False
                    return dfs(node.left) and dfs(node.right)
                return dfs(root)
        

        4.7.588 - 2025-08-01 19:27:17 +0300 MSK

        N-Repeated Element in Size 2N Array

        Code

        class Solution:
            def repeatedNTimes(self, nums: List[int]) -> int:
                length = len(nums)
                for k in range(1, 4):
                    for i in range(length - k):
                        if nums[i] == nums[i+k]:
                            return nums[i]
                raise Exception
        

        4.7.589 - 2025-08-01 19:18:48 +0300 MSK

        N-Repeated Element in Size 2N Array

        Code

        class Solution:
            def repeatedNTimes(self, nums: List[int]) -> int:
                enc = set()
                for num in nums:
                    if num in enc:
                        return num
                    enc.add(num)
                raise Exception
        

        4.7.590 - 2025-08-01 19:16:55 +0300 MSK

        Verifying an Alien Dictionary

        Code

        class Solution:
            def isAlienSorted(self, words: List[str], order: str) -> bool:
                pos = {}
                for i, char in enumerate(order):
                    pos[char] = i
                for i in range(len(words) - 1):
                    cur, nxt = words[i], words[i + 1]
                    cur_length, nxt_length = len(cur), len(nxt)
                    for j in range(cur_length):
                        if j >= nxt_length:
                            return False
                        cur_char, nxt_char = cur[j], nxt[j]
                        if cur_char == nxt_char:
                            continue
                        if pos[cur_char] > pos[nxt_char]: 
                            return False
                        break
                return True
        

        4.7.591 - 2025-08-01 17:46:26 +0300 MSK

        Delete Columns to Make Sorted

        Code

        class Solution:
            def minDeletionSize(self, strs: List[str]) -> int:
                res = 0
                for col in range(len(strs[0])):
                    prev = 0
                    for row in range(len(strs)):
                        char = ord(strs[row][col])
                        if char >= prev:
                            prev = char
                        else:
                            res += 1
                            break
                return res
        

        4.7.592 - 2025-08-01 17:40:59 +0300 MSK

        DI String Match

        Code

        class Solution:
            def diStringMatch(self, s: str) -> List[int]:
                length = len(s)
                res = [None] * (length + 1)
                num_i, num_d = 0, length
                for i, char in enumerate(s):
                    if char == "I":
                        res[i] = num_i
                        num_i += 1
                    else:
                        res[i] = num_d
                        num_d -= 1
                res[-1] = num_i
                return res
        

        4.7.593 - 2025-08-01 17:39:13 +0300 MSK

        DI String Match

        Code

        class Solution:
            def diStringMatch(self, s: str) -> List[int]:
                length = len(s)
                res = [None] * (length + 1)
                num_i, num_d = 0, length
                for i, char in enumerate(s):
                    is_i = char == "I"
                    if is_i:
                        res[i] = num_i
                        num_i += 1
                    else:
                        res[i] = num_d
                        num_d -= 1
                    if i != length - 1:
                        continue
                    if is_i:
                        res[i+1] = num_d
                    else:
                        res[i+1] = num_i
                return res
        

        4.7.594 - 2025-08-01 17:12:58 +0300 MSK

        Valid Mountain Array

        Code

        class Solution:
            def validMountainArray(self, arr: List[int]) -> bool:
                length = len(arr)
                if length < 3:
                    return False
                enc_peak = False
                prev = arr[0]
                for i, num in enumerate(arr[1:], 1):
                    if num == prev:
                        return False
                    if not enc_peak and num < prev:
                        enc_peak = True
                    if enc_peak and (num > prev or i == 1):
                        return False   
                    prev = num
                return enc_peak
        

        4.7.595 - 2025-08-01 16:57:25 +0300 MSK

        Unique Email Addresses

        Code

        class Solution:
            def numUniqueEmails(self, emails: List[str]) -> int:
                enc = set()
                for email in emails:
                    name, domain = email.rsplit("@", 1)
                    name = name.split("+", 1)[0].replace(".", "")
                    enc.add("@".join((name, domain)))
                return len(enc)
        

        4.7.596 - 2025-08-01 16:53:59 +0300 MSK

        Long Pressed Name

        Code

        class Solution:
            def isLongPressedName(self, name: str, typed: str) -> bool:
                name_i, typed_i = 0, 0
                name_length, typed_length = len(name), len(typed)
        
                while name_i < name_length and typed_i < typed_length:
                    if name[name_i] == typed[typed_i]:
                        name_i += 1
                        typed_i += 1
                    elif typed_i >= 1 and typed[typed_i] == typed[typed_i - 1]:
                        typed_i += 1
                    else:
                        return False
        
                if name_i != name_length:
                    return False
        
                while typed_i < typed_length:
                    if typed[typed_i] != typed[typed_i - 1]:
                        return False
                    typed_i += 1
        
                return True
        

        4.7.597 - 2025-08-01 16:43:05 +0300 MSK

        Sort Array By Parity II

        Code

        class Solution:
            def sortArrayByParityII(self, nums: List[int]) -> List[int]:
                res = [None] * len(nums)
                i1, i2 = 0, 1
                for num in nums:
                    if num % 2 == 0:
                        res[i1] = num
                        i1 += 2
                    else:
                        res[i2] = num
                        i2 += 2
                return res
        

        4.7.598 - 2025-08-01 16:39:51 +0300 MSK

        Sort Array By Parity II

        Code

        class Solution:
            def sortArrayByParityII(self, nums: List[int]) -> List[int]:
                stack_even, stack_odd = [], []
                for num in nums:
                    if num % 2 == 0:
                        stack_even.append(num)
                    else:
                        stack_odd.append(num)
                for i in range(len(nums)):
                    if i % 2 == 0:
                        nums[i] = stack_even.pop()
                    else:
                        nums[i] = stack_odd.pop()
                return nums
        

        4.7.599 - 2025-08-01 16:33:40 +0300 MSK

        Reverse Only Letters

        Code

        class Solution:
            def reverseOnlyLetters(self, s: str) -> str:
                i, j = 0, len(s) - 1
                res = [None] * len(s)
                while i <= j:
                    char1, char2 = s[i], s[j]
                    if not char1.isalpha():
                        res[i] = char1
                        i += 1
                    elif not char2.isalpha():
                        res[j] = char2
                        j -= 1
                    else:
                        res[i], res[j] = char2, char1
                        i += 1
                        j -= 1
                return "".join(res)
        

        4.7.600 - 2025-08-01 16:24:11 +0300 MSK

        X of a Kind in a Deck of Cards

        Code

        import math
        import functools
        
        class Solution:
            def hasGroupsSizeX(self, deck: List[int]) -> bool:
                freqs = collections.defaultdict(int)
                for num in deck:
                    freqs[num] += 1
                gcd = functools.reduce(math.gcd, freqs.values())
                return gcd > 1
        

        4.7.601 - 2025-08-01 16:02:30 +0300 MSK

        Smallest Range I

        Code

        class Solution:
            def smallestRangeI(self, nums: List[int], k: int) -> int:
                min_num, max_num = min(nums), max(nums)
                diff = max_num - min_num
                res = max(diff - 2 * k, 0)
                return res
        

        4.7.602 - 2025-08-01 16:01:56 +0300 MSK

        Smallest Range I

        Code

        class Solution:
            def smallestRangeI(self, nums: List[int], k: int) -> int:
                min_num, max_num = float("inf"), float("-inf")
                for num in nums:
                    if num > max_num:
                        max_num = num
                    if num < min_num:
                        min_num = num
                diff = max_num - min_num
                res = max(diff - 2 * k, 0)
                return res
        

        4.7.603 - 2025-08-01 15:50:58 +0300 MSK

        Increasing Order Search Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def increasingBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
                if root is None:
                    return None
                def dfs(node: TreeNode) -> tuple[TreeNode, TreeNode]:
                    if node.left:
                        root, tail = dfs(node.left)
                        tail.right = node
                        tail = node
                        node.left = None
                    else:
                        root, tail = node, node
                    if node.right:
                        right_root, right_tail = dfs(node.right)
                        tail.right = right_root
                        tail = right_tail
                    return root, tail
        
                root, tail = dfs(root)
                return root
        

        4.7.604 - 2025-08-01 15:30:00 +0300 MSK

        Surface Area of 3D Shapes

        Code

        class Solution:
            def surfaceArea(self, grid: list[list[int]]) -> int:
                length = len(grid)
                res = 0
                adj_delta = (
                    (-1, 0), (1, 0), (0, -1), (0, 1)
                )
                for row in range(length):
                    for col in range(length):
                        height = grid[row][col]
                        if height == 0:
                            continue
                        res += 2
                        for row_delta, col_delta in adj_delta:
                            adj_row, adj_col = row + row_delta, col + col_delta
                            if 0 <= adj_row < length and 0 <= adj_col < length:
                                adj_height = grid[adj_row][adj_col]
                            else:
                                adj_height = 0
                            if height > adj_height:
                                res += grid[row][col] - adj_height
                return res
        

        4.7.605 - 2025-08-01 14:50:20 +0300 MSK

        Fair Candy Swap

        Code

        class Solution:
            def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
                count1, count2 = sum(aliceSizes), sum(bobSizes)
                delta = (count2 - count1) // 2
                set2 = set(bobSizes)
                for ex1 in aliceSizes:
                    ex2 = ex1 + delta
                    if ex2 in set2:
                        return ex1, ex2
                raise Exception
        

        4.7.606 - 2025-08-01 13:28:24 +0300 MSK

        Uncommon Words from Two Sentences

        Code

        class Solution:
            def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
                freqs = collections.defaultdict(int)
                res = []
                for word in s1.split():
                    freqs[word] += 1
                for word in s2.split():
                    freqs[word] += 1
                for word, freq in freqs.items():
                    if freq == 1:
                        res.append(word)
                return res
        

        4.7.607 - 2025-08-01 13:24:00 +0300 MSK

        Uncommon Words from Two Sentences

        Code

        class Solution:
            def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
                freqs1, freqs2 = defaultdict(int), defaultdict(int)
                words1, words2 = s1.split(" "), s2.split(" ")
                for word in words1:
                    freqs1[word] += 1
                for word in words2:
                    freqs2[word] += 1
                res = []
                for word, freq in freqs1.items():
                    if freq != 1 or word in freqs2:
                        continue
                    res.append(word)
                for word, freq in freqs2.items():
                    if freq != 1 or word in freqs1:
                        continue
                    res.append(word)
                return res
        

        4.7.608 - 2025-08-01 13:12:38 +0300 MSK

        Projection Area of 3D Shapes

        Code

        class Solution:
            def projectionArea(self, grid: list[list[int]]) -> int:
                res = 0
                length = len(grid)
        
                for i in range(length):
                    best_row = 0
                    best_col = 0 
                    for j in range(length):
                        if grid[i][j]: 
                            res += 1 
                        best_row = max(best_row, grid[i][j])
                        best_col = max(best_col, grid[j][i])
        
                    res += best_row + best_col
        
                return res
        

        4.7.609 - 2025-08-01 09:59:43 +0300 MSK

        Lemonade Change

        Code

        class Solution:
            def lemonadeChange(self, bills: List[int]) -> bool:
                change_5, change_10 = 0, 0
                for bill in bills:
                    if bill == 5:
                        change_5 += 1
                    elif bill == 10 and change_5 > 0:
                        change_5 -= 1
                        change_10 += 1
                    elif bill == 10 and change_5 <= 0:
                        return False
                    elif bill == 20 and change_10 > 0 and change_5 > 0:
                        change_10 -= 1
                        change_5 -= 1
                    elif bill == 20 and change_5 >= 3:
                        change_5 -= 3
                    else:
                        return False
                return True
        

        4.7.610 - 2025-08-01 09:40:56 +0300 MSK

        Rectangle Overlap

        Code

        class Solution:
            def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
                def intersect(p_left: int, p_right: int, q_left: int, q_right: int) -> bool:
                    return min(p_right, q_right) > max(p_left, q_left)
                return (
                    intersect(rec1[0], rec1[2], rec2[0], rec2[2]) # width > 0 
                    and intersect(rec1[1], rec1[3], rec2[1], rec2[3]) # height > 0
                )
        

        4.7.611 - 2025-08-01 08:25:54 +0300 MSK

        Flipping an Image

        Code

        class Solution:
            def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
                for row in image:
                    row.reverse()
                    for i in range(len(row)):
                        row[i] ^= 1
                return image
        

        4.7.612 - 2025-08-01 08:21:20 +0300 MSK

        Flipping an Image

        Code

        class Solution:
            def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
                for row in image:
                    row.reverse()
                    for i in range(len(row)):
                        if row[i] == 0:
                            row[i] = 1
                        else:
                            row[i] = 0
                return image
        

        4.7.613 - 2025-08-01 08:13:47 +0300 MSK

        Positions of Large Groups

        Code

        class Solution:
            def largeGroupPositions(self, s: str) -> List[List[int]]:
                res = []
                start = 0
                prev = s[0]
                for i, char in enumerate(itertools.chain(s[1:], " "), 1):
                    if char == prev:
                        continue
                    if i - 1 - start >= 2:
                        res.append((start, i - 1))
                    start = i
                    prev = char
                return res
        

        4.7.614 - 2025-08-01 07:59:37 +0300 MSK

        Goat Latin

        Code

        class Solution:
            def toGoatLatin(self, sentence: str) -> str:
                cur_word = []
                res = []
                i = 0
                for char in itertools.chain(sentence, " "):
                    if char != " ":
                        cur_word.append(char)
                        continue
                    if not cur_word:
                        continue
                    i += 1
                    if cur_word[0].lower() in ("a", "e", "i", "o", "u"):
                        cur_word.append("ma")
                    else:
                        cur_word.append(cur_word[0])
                        cur_word.append("ma")
                        cur_word[0] = ""
                    cur_word.append("a" * i)
                    res.append("".join(cur_word))
                    cur_word.clear()
                return " ".join(res)
        

        4.7.615 - 2025-08-01 07:51:03 +0300 MSK

        Shortest Distance to a Character

        Code

        class Solution:
            def shortestToChar(self, s: str, c: str) -> List[int]:
                indexes = []
                for i, char in enumerate(s):
                    if char == c:
                        indexes.append(i)
                length = len(indexes)
                res = []
                i = 0
                max_diff = float("inf")
                for j, char in enumerate(s):
                    diff1 = abs(indexes[i] - j)
                    if i + 1 >= length:
                        diff2 = max_diff
                    else:
                        diff2 = abs(indexes[i + 1] - j)
                    if diff1 <= diff2:
                        res.append(diff1)
                    else:
                        res.append(diff2)
                        i += 1
                return res
        
                    
        

        4.7.616 - 2025-08-01 07:33:33 +0300 MSK

        Most Common Word

        Code

        class Solution:
            def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
                freqs = defaultdict(int)
                banned_set = set(banned)
                cur_word = []
                for char in itertools.chain(paragraph, "."):
                    if char.isalpha():
                        cur_word.append(char.lower())
                        continue
                    if not cur_word:
                        continue
                    word = "".join(cur_word)
                    if word not in banned_set:
                        freqs[word] += 1
                    cur_word.clear()
                most_freq = ""
                most_freq_freq = 0
                for word, freq in freqs.items():
                    if freq > most_freq_freq:
                        most_freq, most_freq_freq = word, freq
                return most_freq
        

        4.7.617 - 2025-08-01 07:15:40 +0300 MSK

        Pascal’s Triangle

        Code

        class Solution:
            def generate(self, numRows: int) -> List[List[int]]:
                res = [(1, )]
                cur_row = []
                for row in range(1, numRows):
                    cur_row.append(1)
                    prev_row = res[-1]
                    for i in range(1, row):
                        cur_row.append(prev_row[i] + prev_row[i - 1])
                    cur_row.append(1)
                    res.append(tuple(cur_row))
                    cur_row.clear()
                return res
                        
        

        4.7.618 - 2025-07-31 21:28:35 +0300 MSK

        Largest Triangle Area

        Code

        class Solution:
            def largestTriangleArea(self, points: list[int]) -> float:
                def area(p: tuple[int, int], q: tuple[int, int], r: tuple[int, int]) -> float:
                    return 0.5 * abs(
                        (p[0] * q[1]) 
                        + (q[0] * r[1]) 
                        + (r[0] * p[1])
                        - (p[1] * q[0]) 
                        - (q[1] * r[0]) 
                        - (r[1] * p[0])
                    )
        
                res = max(
                    area(p, q, r)
                    for p, q, r in itertools.combinations(points, 3)
                )
                return res
        

        4.7.619 - 2025-07-31 18:46:45 +0300 MSK

        Number of Lines To Write String

        Code

        class Solution:
            def numberOfLines(self, widths: List[int], s: str) -> List[int]:
                line_count = 1
                line_width = 0
                for char in s:
                    char_width = widths[ord(char) - 97]
                    line_width += char_width
                    if line_width > 100:
                        line_width = char_width
                        line_count += 1
                return line_count, line_width
        

        4.7.620 - 2025-07-31 18:31:00 +0300 MSK

        Unique Morse Code Words

        Code

        MORSE = (".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..")
        
        class Solution:
            def uniqueMorseRepresentations(self, words: List[str]) -> int:
                enc = set()
                for word in words:
                    enc.add("".join(MORSE[ord(char) - 97] for char in word))
                return len(enc)
        

        4.7.621 - 2025-07-31 18:29:59 +0300 MSK

        Unique Morse Code Words

        Code

        class Solution:
            def uniqueMorseRepresentations(self, words: List[str]) -> int:
                morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
                enc = set()
                cur_morse = []
                for word in words:
                    cur_morse.clear()
                    for char in word:
                        cur_morse.append(morse[ord(char) - 97])
                    enc.add("".join(cur_morse))
                return len(enc)
        

        4.7.622 - 2025-07-31 18:14:30 +0300 MSK

        Rotate String

        Code

        class Solution:
            def rotateString(self, s: str, goal: str) -> bool:
                if len(s) != len(goal):
                    return False
                return goal in "".join((s, s))
        

        4.7.623 - 2025-07-31 17:53:16 +0300 MSK

        Minimum Distance Between BST Nodes

        Code

        class Solution:
            def minDiffInBST(self, root: TreeNode) -> int:
                self.ans = float('inf')
                self.pred = None
                self.inorder(root)
                return self.ans
        
            def inorder(self, root: TreeNode) -> None:
                if root is None:
                    return
                
                self.inorder(root.left)
                if self.pred is not None:
                    self.ans = min(self.ans, root.val - self.pred)
                self.pred = root.val
                self.inorder(root.right)
        

        4.7.624 - 2025-07-31 17:18:00 +0300 MSK

        Jewels and Stones

        Code

        class Solution:
            def numJewelsInStones(self, jewels: str, stones: str) -> int:
                jewels_set = set(jewels)
                count = 0
                for char in stones:
                    if char in jewels:
                        count += 1
                return count
        

        4.7.625 - 2025-07-31 17:16:38 +0300 MSK

        Toeplitz Matrix

        Code

        class Solution:
            def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
                for i in range(1, len(matrix)):
                    for j in range(1, len(matrix[0])):
                        if matrix[i-1][j-1] != matrix[i][j]:
                            return False
                return True
        

        4.7.626 - 2025-07-31 17:05:37 +0300 MSK

        Shortest Completing Word

        Code

        class Solution:
            def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
                freq = defaultdict(int)
                for char in licensePlate:
                    if char == " " or char.isnumeric():
                        continue
                    freq[char.lower()] += 1
                cur_freq = {}
                shortest = None
                for word in words:
                    cur_freq.clear()
                    cur_freq.update(freq)
                    for char in word:
                        if not cur_freq:
                            break
                        if char not in cur_freq:
                            continue
                        new_freq = cur_freq[char] - 1
                        if new_freq <= 0:
                            cur_freq.pop(char)
                        else:
                            cur_freq[char] = new_freq
                    if not cur_freq and (shortest is None or len(word) < len(shortest)):
                        shortest = word
                return shortest
        

        4.7.627 - 2025-07-31 14:35:36 +0300 MSK

        Largest Number At Least Twice of Others

        Code

        class Solution:
            def dominantIndex(self, nums: List[int]) -> int:
                largest1, largest2 = -1, -1
                largest_i = -1
                for i, num in enumerate(nums):
                    if num == largest2 or num == largest1:
                        continue
                    if num > largest2:
                        largest1 = largest2
                        largest2 = num
                        largest_i = i
                    elif num > largest1:
                        largest1 = num
                if largest1 * 2 <= largest2:
                    return largest_i
                return -1
        

        4.7.628 - 2025-07-31 13:54:58 +0300 MSK

        Flood Fill

        Code

        class Solution:
            def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
                target_color = image[sr][sc]
                if target_color == color:
                    return image
                length_row = len(image)
                length_col = len(image[0])
                dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
                queue = [(sr, sc)]
                while queue:
                    row, col = queue.pop()
                    if row < 0 or row >= length_row:
                        continue
                    if col < 0 or col >= length_col:
                        continue
                    if image[row][col] != target_color:
                        continue
                    image[row][col] = color
                    for row_delta, col_delta in dirs:
                        queue.append((row + row_delta, col + col_delta))
                return image
        

        4.7.629 - 2025-07-31 13:46:42 +0300 MSK

        Flood Fill

        Code

        class Solution:
            def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
                target_color = image[sr][sc]
                enc = set()
                length_row = len(image)
                length_col = len(image[0])
                dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
                queue = [(sr, sc)]
                while queue:
                    row, col = queue.pop()
                    if row < 0 or row >= length_row:
                        continue
                    if col < 0 or col >= length_col:
                        continue
                    if (row, col) in enc:
                        continue
                    if image[row][col] != target_color:
                        continue
                    image[row][col] = color
                    enc.add((row, col))
                    for row_delta, col_delta in dirs:
                        queue.append((row + row_delta, col + col_delta))
                return image
        

        4.7.630 - 2025-07-31 13:03:46 +0300 MSK

        Self Dividing Numbers

        Code

        class Solution:
            def selfDividingNumbers(self, left: int, right: int) -> List[int]:
                def self_dividing(num: int) -> bool:
                    if num == 0:
                        return False
                    cur_num = num
                    while cur_num > 0:
                        mod = cur_num % 10
                        cur_num //= 10
                        if mod == 0 or num % mod > 0:
                            return False
                    return True
                ans = []
                for n in range(left, right + 1):
                    if self_dividing(n):
                        ans.append(n)
                return ans
        

        4.7.631 - 2025-07-31 11:07:49 +0300 MSK

        Degree of an Array

        Code

        class Solution:
            def findShortestSubArray(self, nums: List[int]) -> int:
                left, right, freq = defaultdict(int), defaultdict(int), defaultdict(int)
                max_freq = 0
                for i, num in enumerate(nums):
                    if num not in left:
                        left[num] = i
                    right[num] = i
                    freq[num] += 1
                    max_freq = max(max_freq, freq[num])
                min_length = len(nums)
                for num, num_freq in freq.items():
                    if num_freq != max_freq:
                        continue
                    min_length = min(min_length, right[num] - left[num] + 1)
                return min_length
        

        4.7.632 - 2025-07-31 11:00:20 +0300 MSK

        Count Binary Substrings

        Code

        class Solution:
            def countBinarySubstrings(self, s: str) -> int:
                groups = [1]
                for i in range(1, len(s)):
                    if s[i-1] != s[i]:
                        groups.append(1)
                    else:
                        groups[-1] += 1
        
                ans = 0
                for i in range(1, len(groups)):
                    ans += min(groups[i-1], groups[i])
                return ans
        

        4.7.633 - 2025-07-31 10:28:31 +0300 MSK

        Baseball Game

        Code

        class Solution:
            def calPoints(self, operations: List[str]) -> int:
                stack = []
                stack_sum = 0
                for op in operations:
                    if op.isnumeric() or op.startswith("-"):
                        new_score = int(op)
                        stack.append(new_score)
                        stack_sum += new_score
                    elif op == "+":
                        new_score = stack[-1] + stack[-2]
                        stack_sum += new_score
                        stack.append(new_score)
                    elif op == "D":
                        new_score = stack[-1] * 2
                        stack_sum += new_score
                        stack.append(new_score)
                    elif op == "C":
                        stack_sum -= stack[-1]
                        stack.pop()
                    else:
                        raise Exception(op)
                return stack_sum
        

        4.7.634 - 2025-07-31 10:04:49 +0300 MSK

        Bitwise ORs of Subarrays

        Code

        class Solution:
            def subarrayBitwiseORs(self, arr: List[int]) -> int:
                ors = set()
                cur = {0}
                for num in arr:
                    cur = {num | cur_num for cur_num in cur} | {num}
                    ors |= cur
                return len(ors)
        

        4.7.635 - 2025-07-30 22:05:38 +0300 MSK

        Valid Palindrome II

        Code

        class Solution:
            def validPalindrome(self, s: str) -> bool:
                def check(i: int, j: int) -> bool:
                    while i < j:
                        if s[i] != s[j]:
                            return False
                        i, j = i + 1, j - 1
                    return True
        
                i, j = 0, len(s) - 1
                while i < j:
                    if s[i] != s[j]:
                        return check(i + 1, j) or check(i, j - 1)
                    i, j = i + 1, j - 1
                return True
        

        4.7.636 - 2025-07-30 22:00:12 +0300 MSK

        Longest Continuous Increasing Subsequence

        Code

        class Solution:
            def findLengthOfLCIS(self, nums: List[int]) -> int:
                prev = nums[0]
                length = 1
                max_length = 1
                for num in nums[1:]:
                    if num > prev:
                        length += 1
                    else:
                        max_length = max(length, max_length)
                        length = 1
                    prev = num
                return max(length, max_length)
        

        4.7.637 - 2025-07-30 21:55:12 +0300 MSK

        Second Minimum Node In a Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def findSecondMinimumValue(self, root):
                self.ans = float('inf')
                min1 = root.val
        
                def dfs(node):
                    if node:
                        if min1 < node.val < self.ans:
                            self.ans = node.val
                        elif node.val == min1:
                            dfs(node.left)
                            dfs(node.right)
        
                dfs(root)
                return self.ans if self.ans < float('inf') else -1
        

        4.7.638 - 2025-07-30 21:02:37 +0300 MSK

        Robot Return to Origin

        Code

        class Solution:
            def judgeCircle(self, moves: str) -> bool:
                row, col = 0, 0
                coords = {
                    "R": (0, 1),
                    "L": (0, -1),
                    "U": (1, 0),
                    "D": (-1, 0)           
                }
                for move in moves:
                    row_delta, col_delta = coords[move]
                    row += row_delta
                    col += col_delta
                return row == 0 and col == 0
        

        4.7.639 - 2025-07-30 20:59:49 +0300 MSK

        Maximum Product of Three Numbers

        Code

        class Solution:
            def maximumProduct(self, nums: List[int]) -> int:
                nums.sort()
                pos_res = nums[-1] * nums[-2] * nums[-3]
                if nums[0] >= 0:
                    return pos_res
                neg_res = nums[0] * nums[1] * nums[-1]
                return max(pos_res, neg_res)
        

        4.7.640 - 2025-07-30 20:52:44 +0300 MSK

        Swap Salary

        Code

        UPDATE
            Salary
        SET
            sex = (
                CASE
                    WHEN
                        sex = 'f'
                    THEN
                        'm'
                    ELSE
                        'f'
                END
            );
        

        4.7.641 - 2025-07-30 20:47:51 +0300 MSK

        Not Boring Movies

        Code

        SELECT
            id, movie, description, rating
        FROM
            Cinema
        WHERE
            description != 'boring'
            AND id % 2 != 0
        ORDER BY
            rating DESC;
        

        4.7.642 - 2025-07-30 20:42:31 +0300 MSK

        Biggest Single Number

        Code

        WITH nums AS (
            SELECT 
                num
            FROM 
                MyNumbers
            GROUP BY 
                num
            HAVING 
                COUNT(num) = 1
        ) 
        SELECT 
            MAX(num) AS num
        FROM 
            nums;
        

        4.7.643 - 2025-07-30 20:35:12 +0300 MSK

        Merge Two Binary Trees

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
                if root1 is None:
                    return root2
                if root2 is None:
                    return root1
                queue = [(root1, root2)]
                while queue:
                    node1, node2 = queue.pop()
                    if node1 is None or node2 is None:
                        continue
                    node1.val += node2.val
                    if node1.left is None:
                        node1.left = node2.left
                    else:
                        queue.append((node1.left, node2.left))
                    if node1.right is None:
                        node1.right = node2.right
                    else:
                        queue.append((node1.right, node2.right))
                return root1
        

        4.7.644 - 2025-07-30 20:27:09 +0300 MSK

        Merge Two Binary Trees

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
                def dfs(node1: Optional[TreeNode], node2: Optional[TreeNode]) -> None:
                    if node1 is None:
                        return node2
                    if node2 is None:
                        return node1
                    node1.val += node2.val
                    node1.left = dfs(node1.left, node2.left)
                    node1.right = dfs(node1.right, node2.right)
                    return node1
                
                return dfs(root1, root2)
        

        4.7.645 - 2025-07-30 20:12:39 +0300 MSK

        Triangle Judgement

        Code

        SELECT
            x, y, z, ( 
                CASE
                    WHEN 
                        ((x+y+z) - GREATEST(x,y,z)) > GREATEST(x,y,z) 
                    THEN 
                        'Yes' 
                    ELSE 
                        'No'
                END
            ) AS triangle
        FROM 
            Triangle;
        

        4.7.646 - 2025-07-30 20:09:55 +0300 MSK

        Triangle Judgement

        Code

        (
            SELECT
                x, y, z, 'Yes' AS triangle
            FROM
                Triangle
            WHERE 
                (x + y > z) AND (y + z > x) AND (z + x > y)
        ) UNION (
            SELECT 
                x, y, z, 'No' AS triangle
            FROM
                Triangle
            WHERE (x + y <= z) OR (y + z <= x) OR (z + x <= y)
        );
        

        4.7.647 - 2025-07-30 20:05:18 +0300 MSK

        Sales Person

        Code

        SELECT 
            sales_person.name
        FROM (
            Orders orders
            JOIN 
                Company company
            ON 
                orders.com_id = company.com_id
                AND company.name = 'RED'
            RIGHT JOIN 
                SalesPerson sales_person
            ON 
                sales_person.sales_id = orders.sales_id
        )
        WHERE
            orders.sales_id IS NULL;
        

        4.7.648 - 2025-07-30 19:52:43 +0300 MSK

        Minimum Index Sum of Two Lists

        Code

        class Solution:
            def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
                indexes = {}
                res = []
                if len(list1) > len(list2):
                    first, second = list2, list1
                else:
                    first, second = list1, list2
                for i, string in enumerate(first):
                    indexes[string] = i
                min_sum = float("inf")
                res = []
                for j, string in enumerate(second):
                    if string not in indexes:
                        continue
                    cur_sum = indexes[string] + j
                    if cur_sum < min_sum:
                        res.clear()
                        res.append(string)
                        min_sum = cur_sum
                    elif cur_sum == min_sum:
                        res.append(string)
                return res
        

        4.7.649 - 2025-07-30 19:27:05 +0300 MSK

        Range Addition II

        Code

        class Solution:
            def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
                min_row = m
                min_col = n
                for range_row, range_col in ops:
                    min_row = min(min_row, range_row)
                    min_col = min(min_col, range_col)
                return min_row * min_col
        

        4.7.650 - 2025-07-30 19:18:29 +0300 MSK

        Classes With at Least 5 Students

        Code

        SELECT 
            class
        FROM 
            Courses
        GROUP BY 
            class
        HAVING 
            COUNT(class) >= 5;
        

        4.7.651 - 2025-07-30 19:14:46 +0300 MSK

        Big Countries

        Code

        SELECT
            World.name, World.population, World.area
        FROM
            World
        WHERE
            World.area >= 3000000
            OR World.population >= 25000000;
        

        4.7.652 - 2025-07-30 19:11:57 +0300 MSK

        Longest Harmonious Subsequence

        Code

        class Solution:
            def findLHS(self, nums):
                freq = defaultdict(int)
                max_length = 0
                for num in nums:
                    freq[num] += 1
                for num in freq:
                    nxt = num + 1
                    if nxt not in freq:
                        continue
                    cur_length = freq[num] + freq[nxt]
                    max_length = max(max_length, cur_length)
                return max_length 
        

        4.7.653 - 2025-07-30 18:59:58 +0300 MSK

        N-ary Tree Postorder Traversal

        Code

        """
        # Definition for a Node.
        class Node:
            def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
                self.val = val
                self.children = children
        """
        
        class Solution:
            def postorder(self, root: 'Node') -> List[int]:
                if root is None:
                    return []
                res = []
                queue = [root]
                while queue:
                    node = queue.pop()
                    res.append(node.val)
                    for child in node.children:
                        queue.append(child)
                res.reverse()
                return res
        

        4.7.654 - 2025-07-30 18:49:52 +0300 MSK

        N-ary Tree Postorder Traversal

        Code

        """
        # Definition for a Node.
        class Node:
            def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
                self.val = val
                self.children = children
        """
        
        class Solution:
            def postorder(self, root: 'Node') -> List[int]:
                res = []
                def dfs(node: Node, res: list[int]) -> None:
                    if node is None:
                        return
                    for child in node.children:
                        dfs(child, res)
                    res.append(node.val)
                dfs(root, res)
                return res
        

        4.7.655 - 2025-07-30 18:45:39 +0300 MSK

        N-ary Tree Preorder Traversal

        Code

        """
        # Definition for a Node.
        class Node:
            def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
                self.val = val
                self.children = children
        """
        
        class Solution:
            def preorder(self, root: 'Node') -> List[int]:
                if root is None:
                    return []
                res = []
                queue = [root]
                while queue:
                    node = queue.pop()
                    res.append(node.val)
                    queue.extend(reversed(node.children))
                return res
        

        4.7.656 - 2025-07-30 18:44:00 +0300 MSK

        N-ary Tree Preorder Traversal

        Code

        """
        # Definition for a Node.
        class Node:
            def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
                self.val = val
                self.children = children
        """
        
        class Solution:
            def preorder(self, root: 'Node') -> List[int]:
                if root is None:
                    return []
                res = []
                queue = deque((root, ))
                while queue:
                    node = queue.popleft()
                    res.append(node.val)
                    queue.extendleft(reversed(node.children))
                return res
        

        4.7.657 - 2025-07-30 18:35:45 +0300 MSK

        N-ary Tree Preorder Traversal

        Code

        """
        # Definition for a Node.
        class Node:
            def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
                self.val = val
                self.children = children
        """
        
        class Solution:
            def preorder(self, root: 'Node') -> List[int]:
                res = []
                def dfs(node: Optional[Node], res: list[int]) -> None:
                    if node is None:
                        return
                    res.append(node.val)
                    for child in node.children:
                        dfs(child, res)
                dfs(root, res)
                return res
        

        4.7.658 - 2025-07-30 18:32:15 +0300 MSK

        Customer Placing the Largest Number of Orders

        Code

        SELECT 
            Orders.customer_number
        FROM 
            Orders
        GROUP BY 
            Orders.customer_number
        ORDER BY 
            COUNT(Orders.customer_number) DESC
        LIMIT 
            1;
        

        4.7.659 - 2025-07-30 18:31:28 +0300 MSK

        Customer Placing the Largest Number of Orders

        Code

        SELECT 
            Orders.customer_number
        FROM 
            Orders
        GROUP BY 
            Orders.customer_number
        ORDER BY 
            COUNT(*) DESC
        LIMIT 
            1;
        

        4.7.660 - 2025-07-30 18:25:43 +0300 MSK

        Find Customer Referee

        Code

        SELECT
            Customer.name
        FROM 
            Customer
        WHERE
            Customer.referee_id != 2
            OR Customer.referee_id IS NULL
        

        4.7.661 - 2025-07-30 18:19:10 +0300 MSK

        Employee Bonus

        Code

        SELECT
            Employee.name, Bonus.bonus
        FROM
            Employee
        LEFT JOIN
            Bonus
        ON 
            Employee.empId = Bonus.empId
        WHERE
            Bonus.bonus IS NULL
            OR Bonus.bonus < 1000
        

        4.7.662 - 2025-07-30 18:07:19 +0300 MSK

        Distribute Candies

        Code

        class Solution:
            def distributeCandies(self, candyType: List[int]) -> int:
                types = set()
                max_length = len(candyType) // 2
                for candy in candyType:
                    types.add(candy)
                    if len(types) >= max_length:
                        return max_length
                return len(types)
        

        4.7.663 - 2025-07-30 17:54:50 +0300 MSK

        Subtree of Another Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
                def dfs(node: Optional[TreeNode], sub_node: Optional[TreeNode]) -> bool:
                    if not node and not sub_node:
                        return True
                    if not node or not sub_node:
                        return False
                    if node.val != sub_node.val:
                        return False
                    return dfs(node.left, sub_node.left) and dfs(node.right, sub_node.right)
                
                def dfs2(node: Optional[TreeNode], sub_node: Optional[TreeNode]) -> bool:
                    if dfs(node, sub_node):
                        return True
                    if not node or not sub_node:
                        return False
                    return dfs2(node.left, sub_node) or dfs2(node.right, sub_node)
        
                return dfs2(root, subRoot)
        

        4.7.664 - 2025-07-30 17:36:45 +0300 MSK

        Reshape the Matrix

        Code

        class Solution:
            def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
                if len(mat) * len(mat[0]) != r * c:
                    return mat
                new_mat = [[None] * c for _ in range(r)]
                new_row = 0
                new_col = 0
                for row in mat:
                    for col in row:
                        if new_col == c:
                            new_col = 0
                            new_row += 1
                        new_mat[new_row][new_col] = col
                        new_col += 1
                return new_mat
                        
        

        4.7.665 - 2025-07-30 16:27:11 +0300 MSK

        Binary Tree Tilt

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def findTilt(self, root: Optional[TreeNode]) -> int:
                def dfs(node: Optional[TreeNode]) -> tuple[int, int]:
                    if node is None:
                        return 0, 0
                    left_sum, left_tilt = dfs(node.left)
                    right_sum, right_tilt = dfs(node.right)
                    tilt_sum = left_tilt + right_tilt + abs(left_sum - right_sum)
                    node_sum = node.val + left_sum + right_sum
                    return node_sum, tilt_sum
                _, tilt_sum = dfs(root)
                return tilt_sum
        

        4.7.666 - 2025-07-30 16:07:35 +0300 MSK

        Array Partition

        Code

        class Solution:
            def arrayPairSum(self, nums: List[int]) -> int:
                nums.sort()
                length = len(nums)
                i = 0
                sum = 0
                while i < length:
                    sum += nums[i]
                    i += 2
                return sum
        

        4.7.667 - 2025-07-30 16:04:16 +0300 MSK

        Maximum Depth of N-ary Tree

        Code

        """
        # Definition for a Node.
        class Node:
            def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
                self.val = val
                self.children = children
        """
        
        class Solution:
            def maxDepth(self, root: 'Node') -> int:
                if root is None:
                    return 0
                queue: deque[tuple[Node, int]] = deque(((root, 1),))
                max_depth = 0
                while queue:
                    node, depth = queue.popleft()
                    max_depth = depth
                    for child in node.children:
                        queue.append((child, 1 + depth))
                return max_depth
        

        4.7.668 - 2025-07-30 15:53:02 +0300 MSK

        Maximum Depth of N-ary Tree

        Code

        """
        # Definition for a Node.
        class Node:
            def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
                self.val = val
                self.children = children
        """
        
        class Solution:
            def maxDepth(self, root: 'Node') -> int:
                def dfs(node: Node) -> int:
                    if not node:
                        return 0
                    if not node.children:
                        return 1
                    return 1 + max(dfs(child) for child in node.children)
                return dfs(root)
        

        4.7.669 - 2025-07-30 15:50:06 +0300 MSK

        Student Attendance Record I

        Code

        class Solution:
            def checkRecord(self, s: str) -> bool:
                a_count = 0
                l_count = 0
                for char in s:
                    if char == "P":
                        l_count = 0
                    elif char == "A":
                        a_count += 1
                        l_count = 0
                    elif char == "L":
                        l_count += 1
                    if l_count >= 3 or a_count >= 2:
                        return False
                return True
        

        4.7.670 - 2025-07-30 15:40:51 +0300 MSK

        Reverse String II

        Code

        class Solution:
            def reverseStr(self, s: str, k: int) -> str:
                length = len(s)
                if length == 1:
                    return s
                if length <= k:
                    return s[::-1]
                res = []
                i = 0
                while i < length:
                    new_i = i + 2 * k
                    res.append(s[i+k-1:i:-1])
                    res.append(s[i])
                    res.append(s[i+k:new_i])
                    i = new_i
                return "".join(res)
        

        4.7.671 - 2025-07-30 15:11:27 +0300 MSK

        Longest Uncommon Subsequence I

        Code

        class Solution:
            def findLUSlength(self, a: str, b: str) -> int:
                if a == b:
                    return -1
                else:
                    return max(len(a), len(b))
        

        4.7.672 - 2025-07-30 15:08:16 +0300 MSK

        Longest Subarray With Maximum Bitwise AND

        Code

        class Solution:
            def longestSubarray(self, nums: List[int]) -> int:
                max_val = ans = current_streak = 0
                for num in nums:
                    if max_val < num:
                        max_val = num
                        ans = current_streak = 0
                    if max_val == num:
                        current_streak += 1
                    else:
                        current_streak = 0
                    ans = max(ans, current_streak)
                return ans
        

        4.7.673 - 2025-07-30 15:06:29 +0300 MSK

        Longest Subarray With Maximum Bitwise AND

        Code

        class Solution:
            def longestSubarray(self, nums: List[int]) -> int:
                max_and = max(nums)
                max_length = 0        
                cur_length = 0
                for num in nums:
                    if num == max_and:
                        cur_length += 1
                    else:
                        max_length = max(max_length, cur_length)
                        cur_length = 0
                return max(max_length, cur_length)
        

        4.7.674 - 2025-07-30 14:49:28 +0300 MSK

        Detect Capital

        Code

        class Solution:
            def detectCapitalUse(self, word: str) -> bool:
                length = len(word)
                if length == 1:
                    return True
                def is_cap(char: str) -> bool:
                    res = 65 <= ord(char) <= 90
                    return res
                first_cap, second_cap = is_cap(word[0]), is_cap(word[1])
                if first_cap and second_cap:
                    should_be_cap = True
                elif first_cap and not second_cap:
                    should_be_cap = False
                elif not first_cap and second_cap:
                    return False
                elif not first_cap and not second_cap:
                    should_be_cap = False
                else:
                    raise Exception
                for char in word[2:]:
                    if is_cap(char) != should_be_cap:
                        return False
                return True
        

        4.7.675 - 2025-07-29 21:27:41 +0300 MSK

        Game Play Analysis I

        Code

        SELECT
            player_id, MIN(event_date) as "first_login"
        FROM
            Activity
        GROUP BY
            player_id
        

        4.7.676 - 2025-07-29 21:05:02 +0300 MSK

        Perfect Number

        Code

        class Solution:
            def checkPerfectNumber(self, num: int) -> bool:
                if num == 1:
                    return False
                count = 1
                for i in range(2, int(num**0.5) + 1):
                    if num % i == 0:
                        count += i + (num // i)
                return num == count
        

        4.7.677 - 2025-07-29 20:50:01 +0300 MSK

        Base 7

        Code

        class Solution:
            def convertToBase7(self, num: int) -> str:
                if num > -7 and num < 7:
                    return str(num)
                res_arr = []
                sign = ""
                if num < 0:
                    sign = "-"
                    num = -num
                while num:
                    res_arr.append(str(num % 7))
                    num //= 7
                res = sign + "".join(reversed(res_arr))
                return res
        

        4.7.678 - 2025-07-29 20:45:22 +0300 MSK

        Next Greater Element I

        Code

        class Solution:
            def nextGreaterElement(self, nums1: list[int], nums2: list[int]) -> list[int]:
                stack = []
                greater = {}
                for num in nums2:
                    while stack and num > stack[-1]:
                        greater[stack.pop()] = num
                    stack.append(num)
                for num in stack:
                    greater[num] = -1
                return [greater[num] for num in nums1]
        

        4.7.679 - 2025-07-29 19:17:54 +0300 MSK

        Teemo Attacking

        Code

        class Solution:
            def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
                total = 0
                cur_end = -1
                for second in timeSeries:
                    if second > cur_end:
                        total += duration
                    else:
                        total += duration - (cur_end - second) - 1
                    cur_end = second + duration - 1
                return total
        

        4.7.680 - 2025-07-29 18:55:38 +0300 MSK

        Hamming Distance

        Code

        class Solution:
            def hammingDistance(self, x: int, y: int) -> int:
                count = 0
                while x or y:
                    if x % 2 != y % 2:
                        count += 1
                    x //= 2
                    y //= 2
                return count
        

        4.7.681 - 2025-07-29 18:52:23 +0300 MSK

        Number of Segments in a String

        Code

        class Solution:
            def countSegments(self, s: str) -> int:
                length = len(s)
                count = 0
                is_segment = False
                for char in s:
                    is_space = char == " "
                    if not is_segment and not is_space:
                        is_segment = True
                        count += 1
                    elif is_space:
                        is_segment = False
                return count
        

        4.7.682 - 2025-07-29 18:27:23 +0300 MSK

        Convert a Number to Hexadecimal

        Code

        class Solution:
            def toHex(self, num: int) -> str:
                if num >=0 and num < 10:
                    return str(num)
                if num < 0:
                    num = (1 << 32) + num
                symbols = "0123456789abcdef"
                res = []
                while num > 0:
                    mod = num % 16
                    res.append(symbols[mod])
                    num //= 16
                return "".join(reversed(res))
        

        4.7.683 - 2025-07-29 17:59:54 +0300 MSK

        Binary Watch

        Code

        class Solution:
            def readBinaryWatch(self, num: int) -> list[str]:
                times = []
        
                for h in range(12):
                    for m in range(60):
                        hOnes = bin(h).count('1')
                        mOnes = bin(m).count('1')
                        if hOnes + mOnes == num:
                            times.append(f"{h}:{m:02d}")
        
                return times
        

        4.7.684 - 2025-07-29 17:38:44 +0300 MSK

        Nim Game

        Code

        class Solution:
            def canWinNim(self, n: int) -> bool:
                return n % 4 != 0
        

        4.7.685 - 2025-07-29 17:38:31 +0300 MSK

        Nim Game

        Code

        class Solution:
            def canWinNim(self, n: int) -> bool:
                if n < 3:
                    return True
                True, True, True, False, True, True, True
                1,    2,    3,    4,     5,    6,    7    
                return n % 4 != 0
        

        4.7.686 - 2025-07-29 16:37:09 +0300 MSK

        Delete Duplicate Emails

        Code

        DELETE FROM
            Person
        WHERE 
            id NOT IN (
                SELECT MIN(id) FROM Person 
                GROUP BY email
            )
        ;
        

        4.7.687 - 2025-07-29 16:11:49 +0300 MSK

        Rising Temperature

        Code

        SELECT 
            today.id
        FROM 
            Weather today
        CROSS JOIN 
            Weather yesterday
        WHERE 
            (today.recordDate - yesterday.recordDate = 1)
            AND today.temperature > yesterday.temperature
        

        4.7.688 - 2025-07-29 13:59:48 +0300 MSK

        Smallest Subarrays With Maximum Bitwise OR

        Code

        class Solution:
            def smallestSubarrays(self, nums: List[int]) -> List[int]:
                n = len(nums)
                pos = [-1] * 31
                ans = [0] * n
                for i in range(n - 1, -1, -1):
                    j = i
                    for bit in range(31):
                        if (nums[i] & (1 << bit)) == 0:
                            if pos[bit] != -1:
                                j = max(j, pos[bit])
                        else:
                            pos[bit] = i
                    ans[i] = j - i + 1
                return ans
        

        4.7.689 - 2025-07-28 20:06:14 +0300 MSK

        Employees Earning More Than Their Managers

        Code

        SELECT employee.name AS Employee
        FROM Employee employee
        JOIN Employee manager
        ON employee.managerId = manager.id
        WHERE employee.salary > manager.salary;
        

        4.7.690 - 2025-07-28 19:28:55 +0300 MSK

        Tenth Line

        Code

        awk 'NR == 10 { print $0 }' file.txt
        

        4.7.691 - 2025-07-28 16:53:12 +0300 MSK

        Valid Phone Numbers

        Code

        awk '
        /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ { print $0 }
        /^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$/ { print $0 }
        ' file.txt
        

        4.7.692 - 2025-07-28 16:52:43 +0300 MSK

        Valid Phone Numbers

        Code

        cat file.txt | awk '
        /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ { print $0 }
        /^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$/ { print $0 }
        '
        

        4.7.693 - 2025-07-28 16:45:20 +0300 MSK

        Customers Who Never Order

        Code

        SELECT name as "Customers"
        FROM Customers
        WHERE id NOT IN (
            SELECT customerId 
            FROM Orders
        );
        

        4.7.694 - 2025-07-28 16:35:55 +0300 MSK

        Duplicate Emails

        Code

        SELECT email FROM Person
        GROUP BY email
        HAVING COUNT(email) > 1;
        

        4.7.695 - 2025-07-28 16:25:34 +0300 MSK

        Count Number of Maximum Bitwise-OR Subsets

        Code

        class Solution:
            def countMaxOrSubsets(self, nums: List[int]) -> int:
                max_or_value = 0
                n = len(nums)
                for num in nums:
                    max_or_value |= num
                memo = [[-1] * (max_or_value + 1) for _ in range(n)]
                return self._count_subsets_recursive(nums, 0, 0, max_or_value, memo)
        
            def _count_subsets_recursive(
                self,
                nums: List[int],
                index: int,
                current_or: int,
                target_or: int,
                memo: List[List[int]],
            ) -> int:
                if index == len(nums):
                    return 1 if current_or == target_or else 0
                if memo[index][current_or] != -1:
                    return memo[index][current_or]
                count_without = self._count_subsets_recursive(
                    nums, index + 1, current_or, target_or, memo
                )
                count_with = self._count_subsets_recursive(
                    nums, index + 1, current_or | nums[index], target_or, memo
                )
                res = count_without + count_with
                memo[index][current_or] = res
                return res
        

        4.7.696 - 2025-07-27 19:03:38 +0300 MSK

        Count Hills and Valleys in an Array

        Code

        class Solution:
            def countHillValley(self, nums: List[int]) -> int:
                res = 0
                length = len(nums)
                for i in range(1, length - 1):
                    if nums[i] == nums[i - 1]:
                        continue
                    left = 0
                    for j in range(i - 1, -1, -1):
                        if nums[j] > nums[i]:
                            left = 1
                            break
                        elif nums[j] < nums[i]:
                            left = -1
                            break
                    right = 0
                    for j in range(i + 1, length):
                        if nums[j] > nums[i]:
                            right = 1
                            break
                        elif nums[j] < nums[i]:
                            right = -1
                            break
                    if left == right and left != 0:
                        res += 1
                return res
        

        4.7.697 - 2025-07-26 18:50:49 +0300 MSK

        Maximize Subarrays After Removing One Conflicting Pair

        Code

        class Solution:
            def maxSubarrays(self, n: int, conflictingPairs: List[List[int]]) -> int:
                bMin1 = [2**31 - 1] * (n + 1)
                bMin2 = [2**31 - 1] * (n + 1)
                for pair in conflictingPairs:
                    a = min(pair[0], pair[1])
                    b = max(pair[0], pair[1])
                    if bMin1[a] > b:
                        bMin2[a] = bMin1[a]
                        bMin1[a] = b
                    elif bMin2[a] > b:
                        bMin2[a] = b
                res = 0
                ib1 = n
                b2 = 0x3FFFFFFF
                delCount = [0] * (n + 1)
                for i in range(n, 0, -1):
                    if bMin1[ib1] > bMin1[i]:
                        b2 = min(b2, bMin1[ib1])
                        ib1 = i
                    else:
                        b2 = min(b2, bMin1[i])
                    res += min(bMin1[ib1], n + 1) - i
                    delCount[ib1] += min(min(b2, bMin2[ib1]), n + 1) - min(
                        bMin1[ib1], n + 1
                    )
                return res + max(delCount)
        

        4.7.698 - 2025-07-26 18:48:20 +0300 MSK

        Ugly Number

        Code

        class Solution(object):
            def isUgly(self, n):
                if n <= 0:
                    return False
                
                while n % 2 == 0:
                    n //= 2
                while n % 3 == 0:
                    n //= 3
                while n % 5 == 0:
                    n //= 5
                
                return n == 1
        

        4.7.699 - 2025-07-25 13:23:28 +0300 MSK

        1-bit and 2-bit Characters

        Code

        class Solution(object):
            def isOneBitCharacter(self, bits):
                i = 0
                while i < len(bits) - 1:
                    i += bits[i] + 1
                return i == len(bits) - 1
        

        4.7.700 - 2025-07-25 13:15:13 +0300 MSK

        To Lower Case

        Code

        class Solution:
            def toLowerCase(self, s: str) -> str:
                return s.lower()
        

        4.7.701 - 2025-07-25 13:14:11 +0300 MSK

        Kth Largest Element in a Stream

        Code

        class KthLargest:
        
            def __init__(self, k: int, nums: List[int]):
                if len(nums) < k:
                    nums.extend((float("-inf"),) * (k - len(nums)))
                nums.sort()
                self._nums: list[int] = nums[-k:]
                self._k: int = k
                
            def add(self, val: int) -> int:
                if val > self._nums[0]:
                    self._nums[0] = val
                    self._nums.sort()
                return self._nums[-self._k]
        
        # Your KthLargest object will be instantiated and called as such:
        # obj = KthLargest(k, nums)
        # param_1 = obj.add(val)
        

        4.7.702 - 2025-07-25 12:37:39 +0300 MSK

        Number of Students Doing Homework at a Given Time

        Code

        class Solution:
            def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
                count = 0
                for start, end in zip(startTime, endTime):
                    if queryTime >= start and queryTime <= end:
                        count += 1
                return count
        

        4.7.703 - 2025-07-25 12:29:53 +0300 MSK

        Count Negative Numbers in a Sorted Matrix

        Code

        class Solution:
            def countNegatives(self, grid: List[List[int]]) -> int:
                count = 0
                for i, row in enumerate(grid):
                    for j, num in enumerate(row):
                        if num < 0:
                            count += len(row) - j
                            break 
                return count
        

        4.7.704 - 2025-07-25 12:18:12 +0300 MSK

        Combine Two Tables

        Code

        SELECT firstName, lastName, city, state 
        FROM Person LEFT JOIN Address 
            ON Person.personId = Address.personId
        

        4.7.705 - 2025-07-25 12:07:53 +0300 MSK

        Delete Characters to Make Fancy String

        Code

        class Solution:
            def makeFancyString(self, s: str) -> str:
                length = len(s)
                if length < 3:
                    return s
                prev_char, prev_char_count = "", 0
                res = []
                for char in s:
                    if char != prev_char:
                        prev_char = char
                        prev_char_count = 1
                        res.append(char)
                    elif prev_char_count < 2:
                        prev_char_count += 1
                        res.append(char)
                return "".join(res)
        

        4.7.706 - 2025-07-25 11:57:05 +0300 MSK

        Maximum Erasure Value

        Code

        class Solution:
            def maximumUniqueSubarray(self, nums: List[int]) -> int:
                sub: deque[int] = deque()
                sub_nums: set[int] = set()
                cur_sum: int = 0
                max_sum: int = 0
                for num in nums:
                    while num in sub_nums:
                        sub_num = sub.popleft()
                        sub_nums.remove(sub_num)
                        cur_sum -= sub_num
                    sub.append(num)
                    sub_nums.add(num)
                    cur_sum += num
                    max_sum = max(cur_sum, max_sum)
                return max_sum
                        
                    
        

        4.7.707 - 2025-07-25 09:50:01 +0300 MSK

        Maximum Unique Subarray Sum After Deletion

        Code

        class Solution:
            def maxSum(self, nums: List[int]) -> int:
                if len(nums) == 1:
                    return nums[0]
                nums.sort()
                if nums[-1] <= 0:
                    return nums[-1]
                res = 0
                if nums[0] > 0:
                    res = nums[0]
                for i, num in enumerate(nums[1:], 1):
                    if num <= 0 or num == nums[i - 1]:
                        continue
                    res += num
                return res
        

        4.7.708 - 2025-07-24 18:52:24 +0300 MSK

        Maximum Score From Removing Substrings

        Code

        class Solution:
            def maximumGain(self, s: str, x: int, y: int) -> int:
                total_score = 0
                high_priority_pair = "ab" if x > y else "ba"
                low_priority_pair = "ba" if high_priority_pair == "ab" else "ab"
        
                # First pass: remove high priority pair
                string_after_first_pass = self.remove_substring(s, high_priority_pair)
                removed_pairs_count = (len(s) - len(string_after_first_pass)) // 2
        
                # Calculate score from first pass
                total_score += removed_pairs_count * max(x, y)
        
                # Second pass: remove low priority pair
                string_after_second_pass = self.remove_substring(
                    string_after_first_pass, low_priority_pair
                )
                removed_pairs_count = (
                    len(string_after_first_pass) - len(string_after_second_pass)
                ) // 2
        
                # Calculate score from second pass
                total_score += removed_pairs_count * min(x, y)
        
                return total_score
        
            def remove_substring(self, input: str, target_pair: str) -> str:
                char_stack = []
        
                # Iterate through each character in the input string
                for current_char in input:
                    # Check if current character forms the target pair with the top of the stack
                    if (
                        current_char == target_pair[1]
                        and char_stack
                        and char_stack[-1] == target_pair[0]
                    ):
                        char_stack.pop()  # Remove the matching character from the stack
                    else:
                        char_stack.append(current_char)
        
                # Reconstruct the remaining string after removing target pairs
                return "".join(char_stack)
        

        4.7.709 - 2025-07-24 17:40:53 +0300 MSK

        Minimum Score After Removals on a Tree

        Code

        class Solution:
            def calc(self, part1: int, part2: int, part3: int) -> int:
                return max(part1, part2, part3) - min(part1, part2, part3)
        
            def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:
                length = len(nums)
                parent_to_child: list[int] = [[] for _ in range(length)]
                for node_1, node_2 in edges:
                    parent_to_child[node_1].append(node_2)
                    parent_to_child[node_2].append(node_1)
        
                total = 0
                for num in nums:
                    total ^= num
        
                res = float("inf")
        
                def dfs2(node: int, parent: int, oth: int, anc: int) -> int:
                    son = nums[node]
                    for child in parent_to_child[node]:
                        if child == parent:
                            continue
                        son ^= dfs2(child, node, oth, anc)
                    if parent == anc:
                        return son
                    nonlocal res
                    res = min(res, self.calc(oth, son, total ^ oth ^ son))
                    return son
        
                def dfs(node: int, parent: int) -> int:
                    son = nums[node]
                    for child in parent_to_child[node]:
                        if child == parent:
                            continue
                        son ^= dfs(child, node)
                    for child in parent_to_child[node]:
                        if child == parent:
                            dfs2(child, node, son, node)
                    return son
        
                dfs(0, -1)
                return res
        

        4.7.710 - 2025-07-20 16:53:28 +0300 MSK

        Delete Duplicate Folders in System

        Code

        class Trie:
            serial: str = ""
            children: dict[str, "Trie"]
        
            def __init__(self) -> None:
                self.children = dict()
        
        
        class Solution:
            def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:
                root = Trie()
                freq = Counter()
        
                for path in paths:
                    cur = root
                    for node in path:
                        if node not in cur.children:
                            cur.children[node] = Trie()
                        cur = cur.children[node]
        
                
                def construct(node: Trie) -> None:
                    if not node.children:
                        return
        
                    serial: list[str] = []
                    for folder, child in node.children.items():
                        construct(child)
                        serial.append(f"{folder}({child.serial})")
        
                    serial.sort()
                    node.serial = "".join(serial)
                    freq[node.serial] += 1
        
                construct(root)
        
                ans = list()
                path = list()
        
                def operate(node: Trie) -> None:
                    if freq[node.serial] > 1:
                        return
                    if path:
                        ans.append(path[:])
        
                    for folder, child in node.children.items():
                        path.append(folder)
                        operate(child)
                        path.pop()
        
                operate(root)
                return ans
        

        4.7.711 - 2025-04-15 16:14:06 +0300 MSK

        Count Good Triplets in an Array

        Code

        from sortedcontainers import SortedList
        from typing import List
        
        class Solution:
            def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:
        
                index_map = {num: i for i, num in enumerate(nums2)}
          
                indices = [index_map[num] for num in nums1]
        
                left_counts = []
                left_sorted = SortedList()
                for idx in indices:
                    left_counts.append(left_sorted.bisect_left(idx))
                    left_sorted.add(idx)
        
                right_counts = []
                right_sorted = SortedList()
                for idx in reversed(indices):
                    right_counts.append(len(right_sorted) - right_sorted.bisect_right(idx))
                    right_sorted.add(idx)
                right_counts.reverse() 
                
                return sum(left * right for left, right in zip(left_counts, right_counts))
        

        4.7.712 - 2025-04-14 19:45:07 +0300 MSK

        Count Good Triplets

        Code

        class Solution:
            def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
                ans = 0
                n = len(arr)
                total = [0] * 1001
                for j in range(n):
                    for k in range(j + 1, n):
                        if abs(arr[j] - arr[k]) <= b:
                            lj, rj = arr[j] - a, arr[j] + a
                            lk, rk = arr[k] - c, arr[k] + c
                            l = max(0, lj, lk)
                            r = min(1000, rj, rk)
                            if l <= r:
                                ans += total[r] if l == 0 else total[r] - total[l - 1]
                    for k in range(arr[j], 1001):
                        total[k] += 1
        
                return ans
        

        4.7.713 - 2025-04-13 17:10:23 +0300 MSK

        Count Good Numbers

        Code

        class Solution:
            def countGoodNumbers(self, n: int) -> int:
                mod = 10**9 + 7
        
                # use fast exponentiation to calculate x^y % mod
                def quickmul(x: int, y: int) -> int:
                    ret, mul = 1, x
                    while y > 0:
                        if y % 2 == 1:
                            ret = ret * mul % mod
                        mul = mul * mul % mod
                        y //= 2
                    return ret
        
                return quickmul(5, (n + 1) // 2) * quickmul(4, n // 2) % mod
        

        4.7.714 - 2025-04-12 19:10:13 +0300 MSK

        Find the Count of Good Integers

        Code

        class Solution(object):
            def __init__(self):
                self.res = 0
                self.visited = set()
        
            def vectorToNumber(self, digits):
                return int(''.join(map(str, digits)))
        
            def totalPermutations(self, freqMap, total):
                res = factorial(total)
                for count in freqMap.values():
                    res //= factorial(count)
                return res
        
            def permsWithZero(self, freqMap, total):
                if freqMap.get(0, 0) == 0:
                    return 0
                freqMap[0] -= 1
                res = factorial(total - 1)
                for count in freqMap.values():
                    res //= factorial(count)
                return res
        
            def genPal(self, palin, left, right, divisor, total):
                if left > right:
                    palinVal = self.vectorToNumber(palin)
                    if palinVal % divisor == 0:
                        freq = Counter(palin)
                        key = tuple(sorted(freq.items()))
                        if key not in self.visited:
                            self.res += self.totalPermutations(freq, total) - self.permsWithZero(freq.copy(), total)
                            self.visited.add(key)
                    return
        
                for dig in range(1 if left == 0 else 0, 10):
                    palin[left] = palin[right] = dig
                    self.genPal(palin, left + 1, right - 1, divisor, total)
        
            def countGoodIntegers(self, n, k):
                self.res = 0
                self.visited.clear()
                self.genPal([0] * n, 0, n - 1, k, n)
                return self.res
        

        4.7.715 - 2025-04-11 20:06:54 +0300 MSK

        Count Symmetric Integers

        Code

        class Solution:
            def countSymmetricIntegers(self, low: int, high: int) -> int:
                count = 0
                for num in range(low, high + 1):
                    s = str(num)
                    if len(s) % 2 == 0:
                        mid = len(s) // 2
                        if sum(map(int, s[:mid])) == sum(map(int, s[mid:])):
                            count += 1
                return count
        

        4.7.716 - 2025-04-10 19:50:16 +0300 MSK

        Count the Number of Powerful Integers

        Code

        class Solution:
            def numberOfPowerfulInt(self, start: int, finish: int, limit: int, suffix: str) -> int:
                def count_powerful_up_to(num: int) -> int:
                    num_str = str(num)
                    suffix_len = len(suffix)
                    prefix_len = len(num_str) - suffix_len
        
                    if prefix_len < 0:
                        return 0
        
                    dp = [[0] * 2 for _ in range(prefix_len + 1)]
        
                    dp[prefix_len][0] = 1
                    suffix_from_num = num_str[prefix_len:]
                    dp[prefix_len][1] = int(suffix_from_num) >= int(suffix)
        
                    for i in range(prefix_len - 1, -1, -1):
                        digit = int(num_str[i])
                        dp[i][0] = (limit + 1) * dp[i + 1][0]
                        if digit <= limit:
                            dp[i][1] = digit * dp[i + 1][0] + dp[i + 1][1]
                        else:
                            dp[i][1] = (limit + 1) * dp[i + 1][0]
        
                    return dp[0][1]
        
                return count_powerful_up_to(finish) - count_powerful_up_to(start - 1)
        

        4.7.717 - 2025-04-09 19:33:13 +0300 MSK

        Minimum Operations to Make Array Values Equal to K

        Code

        class Solution:
            def minOperations(self, nums: List[int], k: int) -> int:
                if not nums:
                    return -1
                nums.sort(reverse=True)
                if nums[-1] < k:
                    return -1
                prev = nums[0]
                if prev == k:
                    return 0
                ops = 0
                for num in nums[1:]:
                    if num == prev:
                        continue
                    ops += 1
                    prev = num
                    if num == k:
                        return ops
                return ops + 1
        

        4.7.718 - 2024-06-28 19:53:30 +0300 MSK

        Maximum Total Importance of Roads

        Code

        class Solution:
            def maximumImportance(self, n: int, roads: List[List[int]]) -> int:
                res = 0
                cost = 1
                conn = [0] * n
                for road in roads:
                    conn[road[0]] += 1
                    conn[road[1]] += 1
        
                conn.sort()
                for con in conn:
                    res += con * cost
                    cost += 1
                return res
        

        4.7.719 - 2024-06-26 18:39:14 +0300 MSK

        Balance a Binary Search Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def balanceBST(self, root: TreeNode) -> TreeNode:
                self.sortedArr = []
                self.inorderTraverse(root)
                return self.sortedArrayToBST(0, len(self.sortedArr) - 1)
        
            def inorderTraverse(self, root: TreeNode) -> None:
                if not root:
                    return
                self.inorderTraverse(root.left)
                self.sortedArr.append(root)
                self.inorderTraverse(root.right)
        
            def sortedArrayToBST(self, start: int, end: int) -> TreeNode:
                if start > end:
                    return None
                mid = (start + end) // 2
                root = self.sortedArr[mid]
                root.left = self.sortedArrayToBST(start, mid - 1)
                root.right = self.sortedArrayToBST(mid + 1, end)
                return root        
        

        4.7.720 - 2024-06-25 20:07:01 +0300 MSK

        Binary Search Tree to Greater Sum Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def bstToGst(self, root: TreeNode) -> TreeNode:
                self.val = 0
                
                def dfs(node):
                    if not node:
                        return
                    
                    dfs(node.right)
                    self.val += node.val
                    node.val = self.val
                    dfs(node.left)
                
                dfs(root)
                return root
        

        4.7.721 - 2024-06-24 15:55:17 +0300 MSK

        Minimum Number of K Consecutive Bit Flips

        Code

        class Solution:
            def minKBitFlips(self, A: List[int], K: int) -> int:
                n, flipped, res = len(A), 0, 0
                fp = [0] * n
                for i in range(n):
                    if i >= K:
                        flipped ^= fp[i - K]
                    if flipped == A[i]:
                        if i + K > n:
                            return -1
                        fp[i] = 1
                        flipped ^= 1
                        res += 1
                return res
        

        4.7.722 - 2024-06-23 14:38:18 +0300 MSK

        Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

        Code

        class Solution:
            def longestSubarray(self, nums: List[int], limit: int) -> int:
                decQ = collections.deque() 
                incQ = collections.deque() 
                ans = 0
                left = 0
        
                for right, num in enumerate(nums):
                    while decQ and num > decQ[-1]:
                        decQ.pop()
        
                    decQ.append(num)
        
                    while incQ and num < incQ[-1]:
                        incQ.pop()
        
                    incQ.append(num)
        
                    while decQ[0] - incQ[0] > limit:
                        if decQ[0] == nums[left]:
                            decQ.popleft()
        
                        if incQ[0] == nums[left]:
                            incQ.popleft()
        
                        left += 1
        
                    ans = max(ans, right - left + 1)
        
                return ans
        

        4.7.723 - 2024-06-22 16:33:20 +0300 MSK

        Count Number of Nice Subarrays

        Code

        class Solution:
            def numberOfSubarrays(self, nums: List[int], k: int) -> int:
                for i in range(len(nums)):
                    nums[i] %= 2
                
                prefix_count = [0] * (len(nums) + 1)
                prefix_count[0] = 1
                s = 0
                ans = 0
                
                for num in nums:
                    s += num
                    if s >= k:
                        ans += prefix_count[s - k]
                    prefix_count[s] += 1
                
                return ans
        

        4.7.724 - 2024-06-21 19:21:07 +0300 MSK

        Grumpy Bookstore Owner

        Code

        class Solution:
            def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
                ans = 0
                total = sum((1 - grumpy[i]) * customers[i] for i in range(len(customers)))
        
                window_all = 0
                window_partial = 0
                for i in range(len(customers)):
                    window_all += customers[i]
                    window_partial += (1 - grumpy[i]) * customers[i]
                    if i + 1 >= minutes:
                        ans = max(ans, total - window_partial + window_all)
                        left = i - minutes + 1
                        window_all -= customers[left]
                        window_partial -= (1 - grumpy[left]) * customers[left]
        
                return ans
        

        4.7.725 - 2024-06-19 19:59:31 +0300 MSK

        Minimum Number of Days to Make m Bouquets

        Code

        class Solution:
            def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
                n=len(bloomDay)
                if m*k>n: return -1
        
                def f(d):
                    len, bouquet=0, 0
                    i=0
                    while i<n:
                        while i<n and bloomDay[i]<=d:
                            len+=1
                            if len==k:
                                bouquet+=1
                                len=0
                            i+=1
                        if i<n and bloomDay[i]>d: len=0
                        if bouquet>m: return True
                        i+=1
                    return bouquet>=m
        
                l, r = min(bloomDay), max(bloomDay)
                while l < r:
                    mid = l + (r - l) // 2
                    if f(mid):
                        r = mid
                    else:
                        l = mid + 1
                return l
                
        

        4.7.726 - 2024-06-17 15:39:57 +0300 MSK

        Sum of Square Numbers

        Code

        from math import sqrt
        
        class Solution:
            def judgeSquareSum(self, c: int) -> bool:
                for a in range(int(sqrt(c)) + 1):  # Iterate through all possible values of `a`
                    b = sqrt(c - a * a)  # Compute `b` as the square root of `c - a^2`
                    if b == int(b):  # Check if `b` is an integer
                        return True  # If `b` is an integer, return true
                return False  # If no such pair `(a, b)` is found, return false
        

        4.7.727 - 2024-06-15 13:32:54 +0300 MSK

        IPO

        Code

        class Solution:
            def findMaximizedCapital(
                self, k: int, w: int, profits: List[int], capital: List[int]
            ) -> int:
                n = len(profits)
                projects = [(capital[i], profits[i]) for i in range(n)]
                projects.sort()
                maxHeap = []
                i = 0
                for _ in range(k):
                    while i < n and projects[i][0] <= w:
                        heapq.heappush(maxHeap, -projects[i][1])
                        i += 1
                    if not maxHeap:
                        break
                    w -= heapq.heappop(maxHeap)
        
                return w
        

        4.7.728 - 2024-06-14 18:54:35 +0300 MSK

        Minimum Increment to Make Array Unique

        Code

        class Solution:
            def minIncrementForUnique(self, nums: List[int]) -> int:
                # nums = [3,2,1,2,1,7]
                #        [1,1,2,2,3,7]
        
                # mySet = set({ num for num in nums }), 2+4
                nums.sort()
                numTracker = 0
                minIncreament = 0
        
                for num in nums:
                    numTracker = max(numTracker, num)
                    minIncreament += numTracker - num
                    numTracker += 1
                return minIncreament
        

        4.7.729 - 2024-06-13 10:32:12 +0300 MSK

        Minimum Number of Moves to Seat Everyone

        Code

        class Solution:
            def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
                seats.sort()
                students.sort()
                moves = 0
        
                for i in range(len(seats)) :
                    moves += abs(seats[i] - students[i])
        
                return moves
        

        4.7.730 - 2024-06-12 19:59:15 +0300 MSK

        Sort Colors

        Code

        class Solution:
            def sortColors(self, nums: List[int]) -> None:
                """
                Do not return anything, modify nums in-place instead.
                """
                zeros, ones, n = 0, 0, len(nums)
                for num in nums:
                    if num == 0:
                        zeros += 1
                    elif num == 1:
                        ones += 1
        
                for i in range(0, zeros):
                    nums[i] = 0
        
                for i in range(zeros, zeros + ones):
                    nums[i] = 1
        
                for i in range(zeros + ones, n):
                    nums[i] = 2
        

        4.7.731 - 2024-06-11 20:57:06 +0300 MSK

        Relative Sort Array

        Code

        class Solution:
            def relativeSortArray(self, arr1, arr2):
                result = []
                
                for i in range(len(arr2)):
                    for j in range(len(arr1)):
                        if arr1[j] == arr2[i]:
                            result.append(arr1[j])
                            arr1[j] = -1
                
                arr1.sort()
                
                for num in arr1:
                    if num != -1:
                        result.append(num)
                        
                return result
        

        4.7.732 - 2024-06-10 13:15:44 +0300 MSK

        Height Checker

        Code

        class Solution:
            def heightChecker(self, heights: List[int]) -> int:
                return sum(h!=s for h, s in zip(heights, sorted(heights)))
        

        4.7.733 - 2024-06-09 13:56:45 +0300 MSK

        Subarray Sums Divisible by K

        Code

        class Solution:
            def subarraysDivByK(self, nums: List[int], k: int) -> int:
                count = 0
                prefix_sum = 0
                prefix_map = {0: 1}  
                
                for num in nums:
                    prefix_sum += num
                    mod = prefix_sum % k
                    if mod < 0:  
                        mod += k
                    if mod in prefix_map:
                        count += prefix_map[mod]
                        prefix_map[mod] += 1
                    else:
                        prefix_map[mod] = 1
                
                return count
        

        4.7.734 - 2024-06-08 22:13:27 +0300 MSK

        Continuous Subarray Sum

        Code

        class Solution:
            def checkSubarraySum(self, nums: List[int], k: int) -> bool:
                remainder_map = {0: -1}  
                cumulative_sum = 0
                
                for i, num in enumerate(nums):
                    cumulative_sum += num
                    remainder = cumulative_sum % k
                    if remainder in remainder_map:
                        if i - remainder_map[remainder] > 1:
                            return True
                    else:
                        remainder_map[remainder] = i
                return False
        

        4.7.735 - 2024-06-07 18:18:51 +0300 MSK

        Replace Words

        Code

        class Solution:
            def replaceWords(self, dict: List[str], sentence: str) -> str:
                roots = set(dict)
                words = sentence.split()
                result = []
        
                for word in words:
                    for i in range(len(word) + 1):
                        prefix = word[:i]
                        if prefix in roots:
                            result.append(prefix)
                            break
                    else:
                        result.append(word)
        
                return ' '.join(result)
        

        4.7.736 - 2024-06-06 18:22:03 +0300 MSK

        Hand of Straights

        Code

        class Solution:
            def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
                # Step 1: Check if grouping is possible
                if len(hand) % groupSize != 0:
                    return False
                
                # Step 2: Count the occurrences of each card
                count = Counter(hand)
                
                # Step 3: Sort the unique card values
                sorted_keys = sorted(count.keys())
                
                # Step 4: Form consecutive groups
                for key in sorted_keys:
                    if count[key] > 0:  # If this card is still available
                        start_count = count[key]
                        # Check and form a group starting from `key`
                        for i in range(key, key + groupSize):
                            if count[i] < start_count:
                                return False
                            count[i] -= start_count
                
                # Step 5: Return True if all groups are formed successfully
                return True
        

        4.7.737 - 2024-06-05 10:32:36 +0300 MSK

        Find Common Characters

        Code

        class Solution:
            def commonChars(self, words: List[str]) -> List[str]:
                result = []
                
                # Check each character from 'a' to 'z'
                for char in range(ord('a'), ord('z') + 1):
                    char = chr(char)
                    min_count = float('inf')  # Start with a very high number
                    
                    # Find the minimum count of the character in all words
                    for word in words:
                        count = word.count(char)  # Count the current character in the current word
                        min_count = min(min_count, count)  # Keep track of the smallest count
                        if min_count == 0:
                            break  # If the character is not in one of the words, we can skip further checking
                    
                    # Add the character to the result list the required number of times
                    result.extend([char] * min_count)
                
                return result
        

        4.7.738 - 2024-06-03 15:40:20 +0300 MSK

        Append Characters to String to Make Subsequence

        Code

        class Solution:
            def appendCharacters(self, s: str, t: str) -> int:
                i, j = 0, 0  # Start both pointers at the beginning of s and t
                
                while i < len(s) and j < len(t):  # Continue until one of the strings is fully scanned
                    if s[i] == t[j]:  # If characters match
                        j += 1  # Move the pointer in t forward
                    i += 1  # Always move the pointer in s forward
                
                return len(t) - j  # The number of characters in t not matched in s
                       
        

        4.7.739 - 2024-06-02 21:31:18 +0300 MSK

        Student Attendance Record II

        Code

        class Solution:
            def checkRecord(self, n: int) -> int:
                # Recursion + Cache
                mod=10**9+7
                #only @cache will lead to MLE
                dp=[[[-1]*3 for _ in range(2)] for _ in range(n+1)]
                def f(i, absent, late):
                    if absent>=2 or late>=3: return 0
                    if i==0: return 1
                    if dp[i][absent][late]!=-1:
                        return dp[i][absent][late]
                    ans=f(i-1, absent, 0)
                    ans+=f(i-1, absent, late+1)
                    ans+=f(i-1, absent+1, 0)
                    dp[i][absent][late]=ans%mod
                    return dp[i][absent][late]
                return f(n, 0, 0)
        

        4.7.740 - 2024-06-01 22:04:19 +0300 MSK

        Single Number III

        Code

        class Solution:
            def singleNumber(self, nums: list[int]) -> list[int]:
                n: int = len(nums)
                result: list[int] = [0, 0]
                index = 0
        
                for i in range(n):
                    found = False
                    for j in range(n):
                        if i != j and nums[i] == nums[j]:
                            found = True
                            break
                    if not found:
                        result[index] = nums[i]
                        index += 1
                        if index == 2:
                            break
        
                return result
        

        4.7.741 - 2024-06-01 22:04:02 +0300 MSK

        Count Triplets That Can Form Two Arrays of Equal XOR

        Code

        class Solution:
            def countTriplets(self, arr: List[int]) -> int:
                n = len(arr)
                prefix = [0] * (n + 1)
                
                for i in range(n):
                    prefix[i + 1] = prefix[i] ^ arr[i]
                
                count = 0
                for i in range(n):
                    for k in range(i + 1, n):
                        if prefix[i] == prefix[k + 1]:
                            count += (k - i)
                
                return count
        

        4.7.742 - 2024-06-01 22:03:45 +0300 MSK

        Maximum Score Words Formed by Letters

        Code

        class Solution:
            def maxScoreWords(
                self, words: List[str], letters: List[str], score: List[int]
            ) -> int:
                lettersCounter = Counter(letters)
                totalScore = 0
        
                def explore(index, letterCounter, currScore):
                    nonlocal totalScore
        
                    totalScore = max(totalScore, currScore)
                    if index == len(words):
                        return
        
                    for i in range(index, len(words)):
                        tmpCounter = copy.deepcopy(letterCounter)
                        word = words[i]
                        wordScore = 0
                        isValid = True
        
                        for ch in word:
                            if ch in tmpCounter and tmpCounter[ch] > 0:
                                tmpCounter[ch] -= 1
                                wordScore += score[ord(ch) - ord("a")]
                            else:
                                isValid = False
                                break
                        if isValid:
                            explore(i + 1, tmpCounter, currScore + wordScore)
        
                explore(0, lettersCounter, 0)
                return totalScore
        

        4.7.743 - 2024-06-01 22:01:30 +0300 MSK

        Score of a String

        Code

        class Solution:
            def scoreOfString(self, s: str) -> int:
                score = 0
                for i in range(len(s) - 1):
                    score += abs(ord(s[i]) - ord(s[i + 1]))
                return score               
        

        4.7.744 - 2024-05-29 12:47:46 +0300 MSK

        Number of Steps to Reduce a Number in Binary Representation to One

        Code

        class Solution:
            def numSteps(self, s: str) -> int:
                steps = 0
                carry = 0
                n = len(s) - 1
                for i in range(n, 0, -1):
                    if int(s[i]) + carry == 1:
                        carry = 1
                        steps += 2
                    else:
                        steps += 1
                return steps + carry
        
                
        

        4.7.745 - 2024-05-28 20:05:20 +0300 MSK

        Get Equal Substrings Within Budget

        Code

        class Solution:
            def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
                n = len(s)
                start = 0
                current_cost = 0
                max_length = 0
        
                for end in range(n):
                    current_cost += abs(ord(s[end]) - ord(t[end]))
        
                    while current_cost > maxCost:
                        current_cost -= abs(ord(s[start]) - ord(t[start]))
                        start += 1
        
                    max_length = max(max_length, end - start + 1)
                
                return max_length
        

        4.7.746 - 2024-05-27 10:56:18 +0300 MSK

        Special Array With X Elements Greater Than or Equal X

        Code

        class Solution:
            def specialArray(self, nums: list[int]) -> int:
                nums.sort()
                n: int = len(nums)
        
                def find_number_of_nums(cur_num) -> int:
                    left: int = 0
                    right: int = n - 1
        
                    first_index: int = n
                    while left <= right:
                        mid: int = (left + right) // 2
        
                        if nums[mid] >= cur_num:
                            first_index = mid
                            right = mid - 1
                        else:
                            left = mid + 1
        
                    return n - first_index
        
                for candidate_number in range(1, n + 1, 1):
                    if candidate_number == find_number_of_nums(candidate_number):
                        return candidate_number
        
                return -1
        

        4.7.747 - 2024-05-26 20:44:15 +0300 MSK

        Student Attendance Record II

        Code

        class Solution:
            def checkRecord(self, n: int) -> int:
                temp: list[list[list[int]]] = [
                    [[-1 for _ in range(3)] for _ in range(2)] for _ in range(n)
                ]  # temp[cur_ind][count_a][count_l]
                MOD: int = 10**9 + 7
        
                def check_all_records(cur_ind, count_a, count_l) -> int:
                    if cur_ind == n:
                        return 1
                    if temp[cur_ind][count_a][count_l] != -1:
                        return temp[cur_ind][count_a][count_l]
                    with_a_next: int = check_all_records(cur_ind + 1, count_a + 1, 0) if count_a == 0 else 0
                    with_l_next: int = 0 if count_l == 2 else check_all_records(cur_ind + 1, count_a, count_l + 1)
                    with_p_next: int = check_all_records(cur_ind + 1, count_a, 0)
                    total: int = (with_a_next + with_l_next + with_p_next) % MOD
        
                    temp[cur_ind][count_a][count_l] = total
                    return total
        
                return check_all_records(0, 0, 0)
        

        4.7.748 - 2024-05-25 22:59:58 +0300 MSK

        Word Break II

        Code

        class Solution:
            def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
                wordSet = set(wordDict)
                @cache
                def helper(t):
                    combos = []
                    if not t:
                        return [""]
                    for i, _ in enumerate(t):
                        w = t[:i+1] 
                        if w in wordSet:
                            combos.extend([
                                f'{w} {sentence}' if sentence else w 
                                for sentence in helper(t[i+1:])
                            ])
                    return combos
                return helper(s)
        

        4.7.749 - 2024-05-21 21:02:08 +0300 MSK

        Subsets

        Code

        class Solution:
            def subsets(self, nums: List[int]) -> List[List[int]]:
                def backtrack(start, path):
                    result.append(path)
                    for i in range(start, len(nums)):
                        backtrack(i + 1, path + [nums[i]])
        
                result = []
                backtrack(0, [])
                return result
        

        4.7.750 - 2024-05-20 13:28:49 +0300 MSK

        Sum of All Subset XOR Totals

        Code

        class Solution:
            def subsetXORSum(self, nums: List[int]) -> int:
                return reduce(operator.or_, nums) * 1 << (len(nums) - 1)
                
        

        4.7.751 - 2024-05-19 15:08:43 +0300 MSK

        Find the Maximum Sum of Node Values

        Code

        class Solution:
            def maximumValueSum(self, nums: list[int], k: int, edges: list[list[int]]) -> int:
                n: int = len(nums)
                temp: list[list[int]] = [[-1 for _ in range(2)] for _ in range(n)]  # temp[current_index(node)][is_even]
        
                def calculate_max(cur_ind, is_even) -> int:  # cur_ind -> cur_index of the tree and is_even represents whether we have already changed (XOR) even or odd number of nodes 
                    if cur_ind == n:  # if we go to node which doesn't exist
                        return 0 if is_even else -float("inf")
                    if temp[cur_ind][is_even] != -1:  # if we've already encountered this state
                        return temp[cur_ind][is_even]
        
                    # checking all possible variants (no XOR or XOR)
                    no_xor = nums[cur_ind] + calculate_max(cur_ind + 1, is_even)  # we don't change the number of XOR nodes
                    with_xor = (nums[cur_ind] ^ k) + calculate_max(cur_ind + 1, not is_even)  # we added 1 XORed node
        
                    mx_possible = max(no_xor, with_xor)
                    temp[cur_ind][is_even] = mx_possible
                    return mx_possible
        
                return calculate_max(0, 1)  # is_even == 1 because we have XORed 0 nodes which is even
        

        4.7.752 - 2024-05-18 20:24:14 +0300 MSK

        Distribute Coins in Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def distributeCoins(self, root: Optional[TreeNode]) -> int:
                #move coins to parent DFS
                def f(root, parent):
                    if root==None: return 0
                    moves=f(root.left, root)+f(root.right, root)
                    x=root.val-1
                    if parent!=None: parent.val+=x
                    moves+=abs(x)
                    return moves
                return f(root, None)
        

        4.7.753 - 2024-05-17 21:25:39 +0300 MSK

        Delete Leaves With a Given Value

        Code

        # Definition for a binary tree node.
        # class TreeNode(object):
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        
        class Solution(object):
            def removeLeafNodes(self, root, target):
                """
                :type root: TreeNode
                :type target: int
                :rtype: TreeNode
                """
                if not root:
                    return None
                root.left = self.removeLeafNodes(root.left, target)
                root.right = self.removeLeafNodes(root.right, target)
                if not root.left and not root.right and root.val == target:
                    return None
                return root
        

        4.7.754 - 2024-05-16 18:11:33 +0300 MSK

        Evaluate Boolean Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def helper(self, root):
                if root.val == 0 or root.val == 1:
                    return root.val == 1
                elif root.val == 2:
                    return self.helper(root.left) or self.helper(root.right)
                elif root.val == 3:
                    return self.helper(root.left) and self.helper(root.right)
                return False
                
            def evaluateTree(self, root: Optional[TreeNode]) -> bool:
                return self.helper(root)
        

        4.7.755 - 2024-05-14 12:06:07 +0300 MSK

        Path with Maximum Gold

        Code

        class Solution:
            roww = [1, -1, 0, 0]
            coll = [0, 0, -1, 1]
        
            def dfs(self, grid, x, y, n, m):
                if x < 0 or x >= n or y < 0 or y >= m or grid[x][y] == 0:
                    return 0
                
                curr = grid[x][y]
                grid[x][y] = 0
                localMaxGold = curr
        
                for i in range(4):
                    newX = x + self.roww[i]
                    newY = y + self.coll[i]
                    localMaxGold = max(localMaxGold, curr + self.dfs(grid, newX, newY, n, m))
        
                grid[x][y] = curr
                return localMaxGold
        
            def getMaximumGold(self, grid):
                n = len(grid)
                m = len(grid[0])
                maxGold = 0
        
                for i in range(n):
                    for j in range(m):
                        if grid[i][j] != 0:
                            maxGold = max(maxGold, self.dfs(grid, i, j, n, m))
        
                return maxGold
        

        4.7.756 - 2024-05-13 10:22:15 +0300 MSK

        Score After Flipping Matrix

        Code

        class Solution:
            def matrixScore(self, grid: List[List[int]]) -> int:
                n, m = len(grid), len(grid[0])
                res = (1 << (m - 1)) * n
        
                for j in range(1, m):
                    val = 1 << (m - 1 - j)
                    set_count = 0
        
                    for i in range(n):
                        if grid[i][j] == grid[i][0]:
                            set_count += 1
        
                    res += max(set_count, n - set_count) * val
        
                return res
        

        4.7.757 - 2024-05-12 21:39:08 +0300 MSK

        Largest Local Values in a Matrix

        Code

        class Solution:
            def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
                n, res = len(grid), []
        
                for i in range(1, n - 1):
                    temp_row = []
                    for j in range(1, n - 1):
                        temp = 0
        
                        for k in range(i - 1, i + 2):
                            for l in range(j - 1, j + 2):
                                temp = max(temp, grid[k][l])
        
                        temp_row.append(temp)
                    res.append(temp_row)
        
                return res
        

        4.7.758 - 2024-05-08 10:50:28 +0300 MSK

        Relative Ranks

        Code

        import heapq
        
        class Solution:
            def findRelativeRanks(self, score: List[int]) -> List[str]:
                heap = []
                length = len(score)
                scores = [0] * length
                for i in range(length):
                    scores[i] = (score[i], i)
                scores.sort(reverse=True)
                ranks = {0: "Gold Medal", 1: "Silver Medal", 2: "Bronze Medal"}
                for i in range(length):
                    _, idx = scores[i]
                    score[idx] = ranks.get(i, str(i + 1))
                return score
        

        4.7.759 - 2024-05-08 10:39:08 +0300 MSK

        Relative Ranks

        Code

        import heapq
        
        class Solution:
            def findRelativeRanks(self, score: List[int]) -> List[str]:
                heap = []
                for i, athlete_score in enumerate(score):
                    heapq.heappush(heap, (-athlete_score, i))
                i = 0
                ranks = {0: "Gold Medal", 1: "Silver Medal", 2: "Bronze Medal"}
                while heap:
                    _, athlete = heapq.heappop(heap)
                    rank = ranks.get(i, str(i + 1))
                    score[athlete] = rank
                    i += 1
                return score
        

        4.7.760 - 2024-05-07 10:56:39 +0300 MSK

        Double a Number Represented as a Linked List

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
                def func(head):
                    a=head.val*2
                    if head.next:
                        a+=func(head.next)
                    head.val=a%10
                    return a//10
                a=func(head)
                if a:
                    return ListNode(a,head)
                return head
                        
        

        4.7.761 - 2024-05-06 16:47:26 +0300 MSK

        Remove Nodes From Linked List

        Code

        class Solution:
            def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
                cur = head
                stack = []
                while cur:
                    while stack and stack[-1].val < cur.val:
                        stack.pop()
                    stack.append(cur)
                    cur = cur.next
                
                nxt = None
                while stack:
                    cur = stack.pop()
                    cur.next = nxt
                    nxt = cur
                
                return cur
        

        4.7.762 - 2024-05-04 18:08:36 +0300 MSK

        Boats to Save People

        Code

        func numRescueBoats(people []int, limit int) int {
            sort.Ints(people)
        
            numberOfBouts := 0
        
            start := 0
            end := len(people)-1
        
            for start < end {
                if people[start] + people[end] <= limit {
                    numberOfBouts++
                    start++
                }else{
                    numberOfBouts++
                }
                end--
            }
        
            if start == end {
                numberOfBouts++
            }
        
            return numberOfBouts
        }
        

        4.7.763 - 2024-05-03 17:41:51 +0300 MSK

        Compare Version Numbers

        Code

        func compareVersion(version1 string, version2 string) int {
        
        	rev1 := strings.Split(version1, ".")
        	rev2 := strings.Split(version2, ".")
            // fmt.Println(rev1, rev2)
        
        	revInt1 := make([]int, len(rev1))
        	revInt2 := make([]int, len(rev2))
        
        	for i := 0; i < len(rev1); i++ {
        		revInt1[i], _ = strconv.Atoi(rev1[i])
        	}
        	for i := 0; i < len(rev2); i++ {
        		revInt2[i], _ = strconv.Atoi(rev2[i])
        	}
            // fmt.Println(revInt1, revInt2)
        
        	i := 0
        	j := 0
        
        	for i < len(revInt1) && j < len(revInt2) {
        
        		if revInt1[i] < revInt2[j] {
        			return -1
        		} else if revInt1[i] > revInt2[j] {
        			return 1
        		}
        		i++
        		j++
        	}
        
        	for i < len(revInt1) {
        		if revInt1[i] > 0 {
        			return 1
        		}
        		i++
        	}
        	for j < len(revInt2) {
        		if revInt2[j] > 0 {
        			return -1
        		}
        		j++
        	}
        	return 0
        }
        

        4.7.764 - 2024-05-02 19:49:20 +0300 MSK

        Largest Positive Integer That Exists With Its Negative

        Code

        func findMaxK(nums []int) int {
            alreadySeenNums := map[int]bool{}
            res := -1
        
            for _, num := range nums {
                numAbs := int(math.Abs(float64(num)))
        
                if numAbs < res {
                    continue
                }
        
                if alreadySeenNums[-num] {
                    res = numAbs
                } else {
                    alreadySeenNums[num] = true
                }
            }
        
            return res
        }
        

        4.7.765 - 2024-05-01 12:05:11 +0300 MSK

        Find if Path Exists in Graph

        Code

        type UnionFind struct {
            parent []int
            rank   []int
        }
        
        func NewUnionFind(n int) *UnionFind {
            parent := make([]int, n)
            rank := make([]int, n)
            for i := 0; i < n; i++ {
                parent[i] = i
            }
            return &UnionFind{parent, rank}
        }
        
        func (uf *UnionFind) Find(u int) int {
            if uf.parent[u] != u {
                uf.parent[u] = uf.Find(uf.parent[u])
            }
            return uf.parent[u]
        }
        
        func (uf *UnionFind) UnionByRank(u, v int) {
            i := uf.Find(u)
            j := uf.Find(v)
            if i == j {
                return
            }
            if uf.rank[i] < uf.rank[j] {
                uf.parent[i] = j
            } else if uf.rank[i] > uf.rank[j] {
                uf.parent[j] = i
            } else {
                uf.parent[i] = j
                uf.rank[j]++
            }
        }
        
        func validPath(n int, edges [][]int, source int, destination int) bool {
            uf := NewUnionFind(n)
            for _, edge := range edges {
                u, v := edge[0], edge[1]
                uf.UnionByRank(u, v)
            }
            return uf.Find(source) == uf.Find(destination)
        }
        

        4.7.766 - 2024-05-01 12:04:46 +0300 MSK

        Number of Wonderful Substrings

        Code

        func get(c rune) int {
        
            return int(c - 'a')
        
        }
        
        
        
        func wonderfulSubstrings(word string) int64 {
        
            cnt := make([]int64, 1024)
        
            cnt[0] = 1
        
        
        
            curState := 0
        
            res := int64(0)
        
        
        
            for _, c := range word {
        
                curState ^= 1 << get(c)
        
        
        
                res += cnt[curState]
        
                for odd := 'a'; odd <= 'j'; odd++ {
        
                    oddState := curState ^ (1 << get(odd))
        
                    res += cnt[oddState]
        
                }
        
        
        
                cnt[curState]++
        
            }
        
        
        
            return res
        
        }
        

        4.7.767 - 2024-05-01 12:04:24 +0300 MSK

        Sum of Distances in Tree

        Code

        
        func sumOfDistancesInTree(n int, edges [][]int) []int {
        	graph := make(map[int][]int)
        	count := make([]int, n)
        	res := make([]int, n)
        
        	for _, edge := range edges {
        		u, v := edge[0], edge[1]
        		graph[u] = append(graph[u], v)
        		graph[v] = append(graph[v], u)
        	}
        
        	var dfs1 func(cur, parent int)
        	dfs1 = func(cur, parent int) {
        		count[cur] = 1
        		for _, child := range graph[cur] {
        			if child != parent {
        				dfs1(child, cur)
        				count[cur] += count[child]
        				res[cur] += res[child] + count[child]
        			}
        		}
        	}
        
        	var dfs2 func(cur, parent int)
        	dfs2 = func(cur, parent int) {
        		for _, child := range graph[cur] {
        			if child != parent {
        				res[child] = res[cur] + n - 2*count[child]
        				dfs2(child, cur)
        			}
        		}
        	}
        
        	dfs1(0, -1)
        	dfs2(0, -1)
        
        	return res
        }
        

        4.7.768 - 2024-05-01 12:02:52 +0300 MSK

        Reverse Prefix of Word

        Code

        func reversePrefix(word string, ch byte) string {
            var natija string
            for i := 0; i < len(word); i++ {
                if word[i] == ch { 
                    ch_index := i
                    for i >= 0 {
                        natija += string(word[i])
                        i--
                    } 
                    return natija + word[ch_index + 1 : ]
                }
            }    
            return word
        }
        

        4.7.769 - 2024-04-29 21:04:33 +0300 MSK

        Minimum Number of Operations to Make Array XOR Equal to K

        Code

        func minOperations(nums []int, k int) int {
            res := k
            for _, n := range nums {
                res ^= n
            }
            var ans int
            for res > 0 {
                ans += res%2
                res = res >> 1
            }
            return ans
        }
        

        4.7.770 - 2024-04-26 10:34:22 +0300 MSK

        Minimum Falling Path Sum II

        Code

        
        
        type Triplet struct {
        	minSum       int
        	secondMinSum int
        	minSumIndex  int
        }
        
        func minFallingPathSum(grid [][]int) int {
        	return minFallingPathSumHelper(0, grid).minSum
        }
        
        func minFallingPathSumHelper(row int, grid [][]int) Triplet {
        	if row == len(grid) {
        		return Triplet{0, 0, 0}
        	}
        
        	nextRowTriplet := minFallingPathSumHelper(row+1, grid)
        	currentTriplet := Triplet{math.MaxInt32, math.MaxInt32, -1}
        
        	for col := 0; col < len(grid[0]); col++ {
        		var value int
        		if col != nextRowTriplet.minSumIndex {
        			value = grid[row][col] + nextRowTriplet.minSum
        		} else {
        			value = grid[row][col] + nextRowTriplet.secondMinSum
        		}
        
        		if value <= currentTriplet.minSum {
        			currentTriplet.secondMinSum = currentTriplet.minSum
        			currentTriplet.minSum = value
        			currentTriplet.minSumIndex = col
        		} else if value < currentTriplet.secondMinSum {
        			currentTriplet.secondMinSum = value
        		}
        	}
        
        	return currentTriplet
        }
        

        4.7.771 - 2024-04-25 20:32:24 +0300 MSK

        Longest Ideal Subsequence

        Code

        func longestIdealString(s string, k int) int {
        	dp := make([]int, 27)
        	n := len(s)
        
        	for i := n - 1; i >= 0; i-- {
        		cc := s[i]
        		idx := int(cc - 'a')
        		maxi := -1 << 31
        
        		left := max(idx-k, 0)
        		right := min(idx+k, 26)
        
        		for j := left; j <= right; j++ {
        			maxi = max(maxi, dp[j])
        		}
        
        		dp[idx] = maxi + 1
        	}
        
        	max := -1 << 31
        	for _, val := range dp {
        		if val > max {
        			max = val
        		}
        	}
        
        	return max
        }
        
        func max(a, b int) int {
        	if a > b {
        		return a
        	}
        	return b
        }
        
        func min(a, b int) int {
        	if a < b {
        		return a
        	}
        	return b
        }
        

        4.7.772 - 2024-04-24 15:06:12 +0300 MSK

        N-th Tribonacci Number

        Code

        func tribonacci(n int) int {
        	if n < 2 {
        		return n
        	}
        
        	dp := []int{0, 1, 1}
        
        	for i := 3; i <= n; i++ {
        		next := dp[0] + dp[1] + dp[2]
        		dp[0], dp[1], dp[2] = dp[1], dp[2], next
        	}
        
        	return dp[2]
        }
        

        4.7.773 - 2024-04-23 18:14:09 +0300 MSK

        Minimum Height Trees

        Code

        
        
        func findMinHeightTrees(n int, edges [][]int) []int {
        	counts := make([]int, n)
        	links := make([]int, n)
        	for _, edge := range edges {
        		links[edge[0]] ^= edge[1]
        		counts[edge[0]]++
        		links[edge[1]] ^= edge[0]
        		counts[edge[1]]++
        	}
        	Qu := make([]int, 0)
        	dists := make([]int, n)
        	for i := 0; i < n; i++ {
        		if counts[i] == 1 {
        			Qu = append(Qu, i)
        		}
        	}
        	stp := 1
        	for len(Qu) > 0 {
        		size := len(Qu)
        		for j := 0; j < size; j++ {
        			tmp := Qu[0]
        			Qu = Qu[1:]
        			links[links[tmp]] ^= tmp
        			counts[links[tmp]]--
        			if counts[links[tmp]] == 1 {
        				dists[links[tmp]] = int(math.Max(float64(stp), float64(dists[links[tmp]])))
        				Qu = append(Qu, links[tmp])
        			}
        		}
        		stp++
        	}
        	maxDist := 0
        	for _, dist := range dists {
        		if dist > maxDist {
        			maxDist = dist
        		}
        	}
        	res := make([]int, 0)
        	for i, dist := range dists {
        		if dist == maxDist {
        			res = append(res, i)
        		}
        	}
        	return res
        }
        

        4.7.774 - 2024-04-22 10:35:20 +0300 MSK

        Find if Path Exists in Graph

        Code

        type UnionFind struct {
            parent []int
            rank   []int
        }
        
        func NewUnionFind(n int) *UnionFind {
            parent := make([]int, n)
            rank := make([]int, n)
            for i := 0; i < n; i++ {
                parent[i] = i
            }
            return &UnionFind{parent, rank}
        }
        
        func (uf *UnionFind) Find(u int) int {
            if uf.parent[u] != u {
                uf.parent[u] = uf.Find(uf.parent[u])
            }
            return uf.parent[u]
        }
        
        func (uf *UnionFind) UnionByRank(u, v int) {
            i := uf.Find(u)
            j := uf.Find(v)
            if i == j {
                return
            }
            if uf.rank[i] < uf.rank[j] {
                uf.parent[i] = j
            } else if uf.rank[i] > uf.rank[j] {
                uf.parent[j] = i
            } else {
                uf.parent[i] = j
                uf.rank[j]++
            }
        }
        
        func validPath(n int, edges [][]int, source int, destination int) bool {
            uf := NewUnionFind(n)
            for _, edge := range edges {
                u, v := edge[0], edge[1]
                uf.UnionByRank(u, v)
            }
            return uf.Find(source) == uf.Find(destination)
        }
        

        4.7.775 - 2024-04-22 10:16:09 +0300 MSK

        Open the Lock

        Code

        import "strconv"
        
        func openLock(deadends []string, target string) int {
            pow10 := []int{1, 10, 100, 1000}
            visit := make([]int, 10000) // 0: not visited, 1: visited through forward direction, -1: visited through backward direction, 2: deadends
            for _, dead := range deadends {
                num, _ := strconv.Atoi(dead)
                visit[num] = 2
            }
            src := 0
            dest, _ := strconv.Atoi(target)
            steps := 0
            dir := 1
            if visit[src] == 2 || visit[dest] == 2 {
                return -1
            }
            if src == dest {
                return 0
            }
            forward := make([]int, 0)
            backward := make([]int, 0)
            forward = append(forward, src)
            visit[src] = 1
            backward = append(backward, dest)
            visit[dest] = -1
            for len(forward) > 0 && len(backward) > 0 {
                if len(forward) > len(backward) {
                    forward, backward = backward, forward
                    dir = -dir
                }
                steps++
                size := len(forward)
                for j := 0; j < size; j++ {
                    cur := forward[0]
                    forward = forward[1:]
                    for _, p := range pow10 {
                        d := (cur / p) % 10
                        for _, i := range []int{-1, 1} {
                            z := d + i
                            if z == -1 {
                                z = 9
                            } else if z == 10 {
                                z = 0
                            }
                            next := cur + (z-d)*p
                            if visit[next] == -dir {
                                return steps
                            }
                            if visit[next] == 0 {
                                forward = append(forward, next)
                                visit[next] = dir
                            }
                        }
                    }
                }
            }
            return -1
        }
        

        4.7.776 - 2024-04-20 21:02:52 +0300 MSK

        Find All Groups of Farmland

        Code

        func findFarmland(land [][]int) [][]int {
        	result := [][]int{}
        	m, n := len(land), len(land[0])
        	findFarmlandCoordinates := func(row, col int) []int {
        		coordinates := []int{row, col}
        		r, c := row, col
        		for r < m && land[r][col] == 1 {
        			r++
        		}
        		for c < n && land[row][c] == 1 {
        			c++
        		}
        		coordinates = append(coordinates, r-1, c-1)
        		for i := row; i < r; i++ {
        			for j := col; j < c; j++ {
        				land[i][j] = 0
        			}
        		}
        		return coordinates
            }
        	for i := 0; i < m; i++ {
        		for j := 0; j < n; j++ {
        			if land[i][j] == 1 {
        				result = append(result, findFarmlandCoordinates(i, j))
        			}
        		}
        	}
        	return result
        }
        

        4.7.777 - 2024-04-19 10:37:47 +0300 MSK

        Island Perimeter

        Code

        func islandPerimeter(grid [][]int) int {
            islands := 0
            neighbors := 0
        
            for i := 0; i < len(grid); i++ {
                for j := 0; j < len(grid[0]); j++ {
                    if grid[i][j] == 1 {
                        islands++
                        if i-1 >= 0 && grid[i-1][j] == 1 {
                            neighbors++
                        }
                        if j-1 >= 0 && grid[i][j-1] == 1 {
                            neighbors++
                        }
                    }
                }
            }
        
            return islands*4 - neighbors*2
        }
        

        4.7.778 - 2024-04-19 10:37:20 +0300 MSK

        Number of Islands

        Code

        func numIslands(grid [][]byte) int {
            if len(grid) == 0 || len(grid[0]) == 0 {
                return 0
            }
            
            rows := len(grid)
            cols := len(grid[0])
            islands := 0
            
            var dfs func(row, col int)
            dfs = func(row, col int) {
                if row < 0 || col < 0 || row >= rows || col >= cols || grid[row][col] != '1' {
                    return
                }
                grid[row][col] = '0'
                dfs(row-1, col)
                dfs(row+1, col)
                dfs(row, col-1)
                dfs(row, col+1)
            }
            
            for row := 0; row < rows; row++ {
                for col := 0; col < cols; col++ {
                    if grid[row][col] == '1' {
                        dfs(row, col)
                        islands++
                    }
                }
            }
            
            return islands
        }
        

        4.7.779 - 2024-04-17 10:49:35 +0300 MSK

        Smallest String Starting From Leaf

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func smallestFromLeaf(root *TreeNode) string {
        	ans := ""
        	var dfs func(node *TreeNode, text string)
        	dfs = func(node *TreeNode, text string) {
        		if node == nil {
        			return
        		}
        		text = string(rune(node.Val + 97)) + text
        		if node.Right == nil && node.Left == nil {
        			if ans == "" || ans > text {
        				ans = text
        			}
        			return
        		}
        		dfs(node.Left, text)
        		dfs(node.Right, text)
        	}
        
        	dfs(root, "")
        	return ans
        }
        

        4.7.780 - 2024-04-16 22:16:34 +0300 MSK

        Add One Row to Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func addOneRow(root *TreeNode, val int, depth int) *TreeNode {
            if root == nil {
                return nil
            }
        
            if depth == 1 {
                root = &TreeNode{Val: val, Left: root}
            } else if (depth == 2) {
                root.Left = &TreeNode{Val: val, Left: root.Left}
                root.Right = &TreeNode{Val: val, Right: root.Right}
            } else {
                addOneRow(root.Left, val, depth - 1)
                addOneRow(root.Right, val, depth - 1)
            }
        
            return root;
        }
        

        4.7.781 - 2024-04-15 09:51:02 +0300 MSK

        Sum Root to Leaf Numbers

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func sumNumbers(root *TreeNode) int {
            return dfs(root, 0)
        }
        
        func dfs(node *TreeNode, num int) int {
            if node == nil {
                return 0
            }
            if node.Left == nil && node.Right == nil {
                return num * 10 + node.Val
            }
            return dfs(node.Left, num * 10 + node.Val) + dfs(node.Right, num * 10 + node.Val)
        }
        

        4.7.782 - 2024-04-15 09:49:56 +0300 MSK

        Sum of Left Leaves

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func sumOfLeftLeaves(root *TreeNode) int {
            if root == nil {
                return 0
            }
        
            left := 0
            if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
                left = root.Left.Val
            }
        
            return left + sumOfLeftLeaves(root.Left) + sumOfLeftLeaves(root.Right)
        }
        

        4.7.783 - 2024-04-13 18:32:47 +0300 MSK

        Maximal Rectangle

        Code

        func maximalRectangle(matrix [][]byte) int {
            heights := make([]int, len(matrix[0]) + 1)
            heights[len(heights)-1] = -1
            mx := 0
            for _, row := range matrix {
                for i := range row {
                    if row[i] == '1' {
                        heights[i]++
                    } else {
                        heights[i] = 0
                    }
                }
        
                stack := []int{}
                for i, currentHeight := range heights {
                    for len(stack) > 0 && heights[stack[len(stack)-1]] > currentHeight {
                        prev := heights[stack[len(stack)-1]]
                        stack = stack[:len(stack)-1]
        
                        width := i
                        if len(stack) > 0 {
                            width = i - stack[len(stack)-1] - 1
                        }
                        mx = max(mx, prev * width)
                    }
                    stack = append(stack, i)
                } 
            }
            return mx
        }
        

        4.7.784 - 2024-04-12 10:40:19 +0300 MSK

        Trapping Rain Water

        Code

        func trap(height []int) int {
        	var waterStored int
        	leftElevationPoint, rightElevationPoint := 0, len(height)-1                                    // pointers for left and right elevations
        	maxLeftElevation, maxRightElevation := height[leftElevationPoint], height[rightElevationPoint] // max value of left and right elevation points
        
        	for leftElevationPoint < rightElevationPoint { // until left elevation point reaches right elevation point or right elevation point reaches left elevation point
        		if maxLeftElevation < maxRightElevation { // if max left elevation is smaller than max right elevation
        			leftElevationPoint++                               // move the left elevation point by 1
        			if height[leftElevationPoint] > maxLeftElevation { // if height of current left elevation after moving is greater than max left elevation
        				maxLeftElevation = height[leftElevationPoint] // swap the max left elevation with current left elevation point value
        			}
        			waterStored += maxLeftElevation - height[leftElevationPoint] // store water with delta of max left elevation and current left elevation
        		} else {
        			rightElevationPoint--                                // decrease the right elevation by 1
        			if height[rightElevationPoint] > maxRightElevation { // if height of current right elevation after decreasing is greater than max right elevation
        				maxRightElevation = height[rightElevationPoint] // swap the max right elevation with current right elevation point value
        			}
        			waterStored += maxRightElevation - height[rightElevationPoint] // store water with delta of max right elevation and current right elevation
        		}
        	}
        
        	return waterStored
        }
        

        4.7.785 - 2024-04-11 13:44:41 +0300 MSK

        Remove K Digits

        Code

        func removeKdigits(num string, k int) string {
        	res := make([]rune, 0)
            
        	for _, c := range num {
        		for len(res) > 0 && res[len(res) - 1] > c && k > 0 {
        			res = res[:len(res) - 1]
        			k--
        		}
        
        		if len(res) > 0 || c != '0' {
        			res = append(res, c)
        		}
        	}
        
        	for len(res) > 0 && k > 0 {
        		res = res[:len(res) - 1]
        		k--
        	}
        
        	if len(res) == 0 {
        		return "0"
        	}
        	return string(res)
        }
        

        4.7.786 - 2024-04-10 13:25:18 +0300 MSK

        Reveal Cards In Increasing Order

        Code

        func deckRevealedIncreasing(deck []int) []int {
        	n := len(deck)
        	sort.Ints(deck)
        
        	res := make([]int, n)
        	queue := make([]int, n)
        
        	for i := range queue {
        		queue[i] = i
        	}
        
        	for _, card := range deck {
        		idx := queue[0]
        		queue = queue[1:]
        		res[idx] = card
        
        		if len(queue) > 0 {
        			queue = append(queue, queue[0])
        			queue = queue[1:]
        		}
        	}
        
        	return res
        }
        

        4.7.787 - 2024-04-09 14:21:46 +0300 MSK

        Time Needed to Buy Tickets

        Code

        func timeRequiredToBuy(tickets []int, k int) int {
            n := len(tickets)
            d := tickets[k]
            res := 0
            for i := 0; i <= k; i++ {
                res += min(d, tickets[i])
            }
            for i := k + 1; i < n; i++ {
                res += min(d - 1, tickets[i])
            }
            return res
        }
        

        4.7.788 - 2024-04-08 11:25:34 +0300 MSK

        Number of Students Unable to Eat Lunch

        Code

        func countStudents(students []int, sandwiches []int) int {
            req := make([]int, 2)
            for _, student := range students {
                req[student]++
            }
        
            for _, sandwich := range sandwiches {
                if req[sandwich] == 0 {
                    return req[1 - sandwich]
                } else {
                    req[sandwich]--
                }
            }
        
            return 0
        }
        

        4.7.789 - 2024-04-07 11:42:18 +0300 MSK

        Valid Parenthesis String

        Code

        func checkValidString(s string) bool {
            open := 0
            openMax := 0
            for _, char := range s {
                switch char {
                case '(':
                    open++
                    openMax++
                case ')':
                    open--
                    openMax--
                default:
                    open--
                    openMax++
                }
                if openMax < 0 {
                    return false
                }
                if open < 0 {
                    open = 0
                }
            }
            return open == 0
        }
        

        4.7.790 - 2024-04-07 11:41:54 +0300 MSK

        Minimum Remove to Make Valid Parentheses

        Code

        type stack struct {
            top   int
            v     []byte
            index []int
        }
        
        func minRemoveToMakeValid(s string) string {
            stc := stack{top: -1}
        
            // collect bad brackets
            for i, v := range s {
                if v == '(' {
                    stc.v = append(stc.v, '(')
                    stc.index = append(stc.index, i)
                    stc.top++
                } else if v == ')' {
                    if stc.top > -1 && stc.v[stc.top] == '(' {
                        stc.v = stc.v[:stc.top]
                        stc.index = stc.index[:stc.top]
                        stc.top--
                    } else {
                        stc.v = append(stc.v, ')')
                        stc.index = append(stc.index, i)
                        stc.top++
                    }
                }
            }
        
            // remove them
            res := []byte{}
            i := 0
            for _, v := range stc.index {
                res = append(res, s[i:v]...)
                i = v + 1
            }
        
            // checking of end
            if len(res) + len(stc.index) < len(s) {
                res = append(res, s[i:]...)
            }
        
            return string(res)
        }
        

        4.7.791 - 2024-04-05 17:17:39 +0300 MSK

        Make The String Great

        Code

        func makeGood(s string) string {
        	stack := make([]byte, 0, len(s))
        	stack = append(stack, s[0])
        	for i := 1; i < len(s); i++ {
        		if len(stack) > 0 && getDiff(stack[len(stack)-1], s[i]) == 32 {
        			stack = stack[:len(stack)-1]
        			continue
        		}
        		stack = append(stack, s[i])
        	}
        	return string(stack)
        }
        
        func getDiff(a, b uint8) uint8 {
        	if b > a {
        		return b - a
        	}
        	return a - b
        }
        

        4.7.792 - 2024-04-04 16:06:45 +0300 MSK

        Maximum Nesting Depth of the Parentheses

        Code

        func maxDepth(s string) int {
            maxDepth := 0
            curDepth := 0
            for _, ch := range s {
                if ch == '(' {
                    curDepth++
                    maxDepth = max(maxDepth, curDepth)
                } else if ch == ')' {
                    curDepth--
                }
            }
            return maxDepth
        }
        

        4.7.793 - 2024-04-03 10:52:54 +0300 MSK

        Word Search

        Code

        func exist(board [][]byte, word string) bool {
            if nLetters := len(board) * len(board[0]); nLetters < len(word) {
                return false
            }
        
            for i := range board {
                for j := range board[i] {
                    if dfs(i, j, 0, board, word, make(map[pair]struct{})) {
                        return true
                    }
                }
            }
        
            return false
        }
        
        type pair struct {
            r, c int
        }
        
        func dfs(r, c, i int, board [][]byte, word string, visited map[pair]struct{}) bool {
            if i == len(word) {
                return true
            }
        
            inBounds := r >= 0 && r < len(board) && c >= 0 && c < len(board[0])
            if _, ok := visited[pair{r, c}]; !inBounds || ok || word[i] != board[r][c] {
                return false
            }
        
            visited[pair{r, c}] = struct{}{}
        
            up := dfs(r+1, c, i+1, board, word, visited)
            down := dfs(r-1, c, i+1, board, word, visited)
            right := dfs(r, c+1, i+1, board, word, visited)
            left := dfs(r, c-1, i+1, board, word, visited)
        
            delete(visited, pair{r, c})
        
            return up || down || right || left
        }
        

        4.7.794 - 2024-04-02 17:28:57 +0300 MSK

        Isomorphic Strings

        Code

        func isIsomorphic(s string, t string) bool {
            map1 := make([]int, 128) // Stores frequency of s
            map2 := make([]int, 128) // Stores frequency of t
        
            for i := 0; i < len(s); i++ {
                sCh := s[i]
                tCh := t[i]
        
                if map1[sCh] == 0 && map2[tCh] == 0 {
                    map1[sCh] = int(tCh)
                    map2[tCh] = int(sCh)
                } else if map1[sCh] != int(tCh) || map2[tCh] != int(sCh) {
                    return false
                }
            }
            return true
        }
        

        4.7.795 - 2024-04-01 18:03:03 +0300 MSK

        Length of Last Word

        Code

        func lengthOfLastWord(s string) int {
            length := len(s)
            count := 0
            for i := length - 1; i >= 0; i-- {
                isSpace := s[i] == ' '
                if isSpace && count != 0 {
                    return count
                } else if isSpace {
                    continue
                }
                count++
            }
            return count
        }
        

        4.7.796 - 2024-03-31 10:58:30 +0300 MSK

        Count Subarrays With Fixed Bounds

        Code

        func countSubarrays(nums []int, minK int, maxK int) int64 {
            var res int64
        	left := 0
        	pmin := -1
        	pmax := -1
        
        	for right, num := range nums {
        		if num < minK || num > maxK {
        			left = right + 1
        			pmin = -1
        			pmax = -1
        		} else {
        			if num == minK {
        				pmin = right
        			}
        			if num == maxK {
        				pmax = right
        			}
        			res += int64(max(0, min(pmin, pmax) - left + 1))
        		}
        	}
        
        	return res
        }
        

        4.7.797 - 2024-03-30 19:24:47 +0300 MSK

        Subarrays with K Different Integers

        Code

        func subarraysWithAtMostKDistinct(nums []int, k int) int {
            if k == 0 {
                return 0
            }
        
            countOccurrence := make(map[int]int)
            differentIntegers := 0
            left := 0
            result := 0
        
            for right := 0; right < len(nums); right++ {
                countOccurrence[nums[right]]++
                if countOccurrence[nums[right]] == 1 {
                    differentIntegers++
                }
        
                for differentIntegers > k {
                    countOccurrence[nums[left]]--
                    if countOccurrence[nums[left]] == 0 {
                        differentIntegers--
                    }
                    left++
                }
        
                result += right - left + 1
            }
            return result
        }
        
        func subarraysWithKDistinct(nums []int, k int) int {
            return subarraysWithAtMostKDistinct(nums, k) - subarraysWithAtMostKDistinct(nums, k-1)
        }
        

        4.7.798 - 2024-03-29 14:30:16 +0300 MSK

        Count Subarrays Where Max Element Appears at Least K Times

        Code

        func countSubarrays(nums []int, k int) int64 {
        	maxValue := 0
        	var maxValueIds []int
        	var ans int64
        
        	for i, x := range nums {
        		if x > maxValue {
        			maxValue, ans, maxValueIds = x, 0, []int{}
        		}
        
        		if x == maxValue {
        			maxValueIds = append(maxValueIds, i)
        		}
        
        		if len(maxValueIds) >= k {
        			ans += int64(maxValueIds[len(maxValueIds)-k]) + 1
        		}
        	}
        
        	return ans
        }
        

        4.7.799 - 2024-03-28 19:02:58 +0300 MSK

        Length of Longest Subarray With at Most K Frequency

        Code

        func maxSubarrayLength(nums []int, k int) int {
            i := 0
            j := 0
            n := len(nums)
            ans := 1
            mp := make(map[int]int)
        
            for i < n {
                mp[nums[i]]++
                for mp[nums[i]] > k {
                    mp[nums[j]]--
                    j++
                }
                if i-j+1 > ans {
                    ans = i - j + 1
                }
                i++
            }
            return ans
        }
        

        4.7.800 - 2024-03-27 18:55:43 +0300 MSK

        Subarray Product Less Than K

        Code

        func numSubarrayProductLessThanK(nums []int, k int) int {
        	if k <= 1 {
        		return 0
        	}
        
        	l := 0
        	p := 1
        	res := 0
        	for r, num := range nums {
        		p *= num
        		for p >= k {
        			p /= nums[l]
        			l++
        		}
                
        		res += r - l + 1
        	}
        
        	return res
        }
        

        4.7.801 - 2024-03-26 10:04:37 +0300 MSK

        First Missing Positive

        Code

        func firstMissingPositive(nums []int) int {
            n := len(nums)
        
        	for i := 0; i < n; i++ {
        		if nums[i] <= 0 || nums[i] > n {
        			nums[i] = n + 1
        		}
        	}
        
        	for i := 0; i < n; i++ {
        		val := abs(nums[i])
        		if val >= 1 && val <= n {
        			flagIndex := val - 1
        			if nums[flagIndex] > 0 {
        				nums[flagIndex] *= -1
        			}
        		}
        	}
        
        	for i := 1; i <= n; i++ {
        		if nums[i - 1] > 0 {
        			return i
        		}
        	}
        
        	return n + 1
        }
        
        func abs(x int) int {
            if x < 0 {
                return -x
            }
            return x
        }
        

        4.7.802 - 2024-03-25 19:23:11 +0300 MSK

        Find All Duplicates in an Array

        Code

        func findDuplicates(nums []int) []int {
            output := []int{}
            for _, num := range nums {
                idx := abs(num)
                if nums[idx-1] < 0 {
                    output = append(output, idx)
                } else {
                    nums[idx-1] *= -1
                }
            }
            return output
        }
        func abs(num int) int {
            if num < 0 {
                return -num
            }
            return num
        }
        

        4.7.803 - 2024-03-24 14:27:34 +0300 MSK

        Find the Duplicate Number

        Code

        func findDuplicate(nums []int) int {
            seen := make(map[int]struct{})
            for _, num := range nums {
                if _, ok := seen[num]; ok {
                    return num
                }
                seen[num] = struct{}{}
            }
            return -1
        }
        

        4.7.804 - 2024-03-24 14:27:17 +0300 MSK

        Find the Duplicate Number

        Code

        func findDuplicate(nums []int) int {
            seen := make(map[int]struct{}, len(nums) - 1)
            for _, num := range nums {
                if _, ok := seen[num]; ok {
                    return num
                }
                seen[num] = struct{}{}
            }
            return -1
        }
        

        4.7.805 - 2024-03-23 20:51:44 +0300 MSK

        Reorder List

        Code

        func reorderList(head *ListNode) {
            if head == nil || head.Next == nil {
                return
            }
        
            middle := midNode(head)
            newHead := middle.Next
            middle.Next = nil
        
            newHead = reverseLinkedList(newHead)
        
            c1 := head
            c2 := newHead
            var f1, f2 *ListNode
        
            for c1 != nil && c2 != nil {
                // Backup
                f1 = c1.Next
                f2 = c2.Next
        
                // Linking
                c1.Next = c2
                c2.Next = f1
        
                // Move
                c1 = f1
                c2 = f2
            }
        }
        
        func midNode(head *ListNode) *ListNode {
            slow := head
            fast := head
        
            for fast.Next != nil && fast.Next.Next != nil {
                slow = slow.Next
                fast = fast.Next.Next
            }
            return slow
        }
        
        func reverseLinkedList(head *ListNode) *ListNode {
            var prev, curr, forw *ListNode = nil, head, nil
        
            for curr != nil {
                forw = curr.Next
                curr.Next = prev
                prev = curr
                curr = forw
            }
            return prev
        }
        

        4.7.806 - 2024-03-22 11:45:00 +0300 MSK

        Palindrome Linked List

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func isPalindrome(head *ListNode) bool {
            nodes := []int{}
            for head != nil {
                nodes = append(nodes, head.Val)
                head = head.Next
            }
            length := len(nodes)
            for i := range(length / 2) {
                start, end := nodes[i], nodes[length-i-1]
                if start != end {
                    return false
                }
            }
            return true
        }
        

        4.7.807 - 2024-03-22 11:41:12 +0300 MSK

        Reverse Linked List

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func reverseList(head *ListNode) *ListNode {
            if head == nil {
                return nil
            }
            cur, next := head, head.Next
            head.Next = nil
            for next != nil {
                cur, next, next.Next = next, next.Next, cur
            }
            return cur
        }
        

        4.7.808 - 2024-03-21 14:09:24 +0300 MSK

        Reverse Linked List

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func reverseList(head *ListNode) *ListNode {
            if head == nil {
                return nil
            }
            cur, next := head, head.Next
            head.Next = nil
            for next != nil {
                cur, next, next.Next = next, next.Next, cur
            }
            return cur
        }
        

        4.7.809 - 2024-03-21 14:05:27 +0300 MSK

        Reverse Linked List

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func reverseList(head *ListNode) *ListNode {
            if head == nil {
                return nil
            }
            cur, next := head, head.Next
            cur.Next = nil
            for next != nil {
                cur, next, next.Next = next, next.Next, cur
            }
            return cur
        }
        

        4.7.810 - 2024-03-21 13:53:28 +0300 MSK

        Merge In Between Linked Lists

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode {
            if list1 == nil {
                return list2 
            }
            list2Head, list2Tail := list2, list2
            for list2 != nil {
                list2Tail = list2
                list2 = list2.Next
            }
            count := 0
            list1Head := list1
            for list1 != nil {
                next := list1.Next
                if count == a - 1 {
                    list1.Next = list2Head
                } else if count == b {
                    list2Tail.Next = list1.Next
                }
                list1 = next
                count++
            }
            return list1Head
        }
        

        4.7.811 - 2024-03-20 21:13:36 +0300 MSK

        Task Scheduler

        Code

        func leastInterval(tasks []byte, n int) int {
        	if n == 0 {
        		return len(tasks)
        	}
        
        	cnt := make([]int, 26)
        	for _, task := range tasks {
        		cnt[task - 'A']++
        	}
        
        	var maxCount, sameMaxCount int
        	for _, c := range cnt {
        		if c > maxCount {
        			maxCount = c
        			sameMaxCount = 1
        		} else if c == maxCount {
        			sameMaxCount++
        		}
        	}
        
        	res := (n + 1) * (maxCount - 1) + sameMaxCount
            if (res > len(tasks)) {
                return res
            } else {
                return len(tasks)
            }
        }
        

        4.7.812 - 2024-03-20 21:12:54 +0300 MSK

        Merge In Between Linked Lists

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode {
            l := list1
            for i := 1; i <= a - 1; i++ {
                l = l.Next
            }
        
            prev := l
            r := l
            for i := a; i <= b + 1; i++ {
                r = r.Next
                prev.Next = nil
                prev = r
            }
        
            list2Tail := list2
            for list2Tail.Next != nil {
                list2Tail = list2Tail.Next
            }
        
            l.Next = list2
            list2Tail.Next = r
        
            return list1
        }
        

        4.7.813 - 2024-03-18 19:30:56 +0300 MSK

        Minimum Number of Arrows to Burst Balloons

        Code

        func findMinArrowShots(points [][]int) int {
            // Sort the balloons based on their end coordinates
            sort.Slice(points, func(i, j int) bool {
                return points[i][1] < points[j][1]
            })
        
            arrows := 1
            prevEnd := points[0][1]
        
            // Count the number of non-overlapping intervals
            for i := 1; i < len(points); i++ {
                if points[i][0] > prevEnd {
                    arrows++
                    prevEnd = points[i][1]
                }
            }
        
            return arrows
        }
        

        4.7.814 - 2024-03-17 12:32:47 +0300 MSK

        Contiguous Array

        Code

        func findMaxLength(nums []int) int {
            hashmap := make(map[int]int)
            zeros, ones, maxLen := 0, 0, 0
            hashmap[0] = -1 
            for i, num := range nums {
                if num == 0 {
                    zeros++
                } else {
                    ones++
                }
                diff := zeros - ones
                if val, ok := hashmap[diff]; ok {
                    maxLen = max(maxLen, i - val)
                } else {
                    hashmap[diff] = i
                }
            }
            return maxLen
        }
        

        4.7.815 - 2024-03-17 12:32:06 +0300 MSK

        Insert Interval

        Code

        func insert(intervals [][]int, newInterval []int) [][]int {
        	var result [][]int
        
            // Iterate through intervals and add non-overlapping intervals before newInterval
        	i := 0
        	for i < len(intervals) && intervals[i][1] < newInterval[0] {
        		result = append(result, intervals[i])
        		i++
        	}
        
            // Merge overlapping intervals
        	for i < len(intervals) && intervals[i][0] <= newInterval[1] {
        		newInterval[0] = int(math.Min(float64(newInterval[0]), float64(intervals[i][0])))
        		newInterval[1] = int(math.Max(float64(newInterval[1]), float64(intervals[i][1])))
        		i++
        	}
        
            // Add merged newInterval
        	result = append(result, newInterval)
        
            // Add non-overlapping intervals after newInterval
        	for i < len(intervals) {
        		result = append(result, intervals[i])
        		i++
        	}
        
        	return result
        }
        

        4.7.816 - 2024-03-15 20:15:18 +0300 MSK

        Product of Array Except Self

        Code

        func productExceptSelf(nums []int) []int {
            n := len(nums)
            res := make([]int, n)
        
            preProduct := 1
            for i := 0; i < n; i++ {
                res[i] = preProduct
                preProduct *= nums[i]
            }
        
            sufProduct := 1
            for i := n - 1; i >= 0; i-- {
                res[i] *= sufProduct
                sufProduct *= nums[i]
            }
        
            return res
        }
        

        4.7.817 - 2024-03-14 19:06:22 +0300 MSK

        Binary Subarrays With Sum

        Code

        func numSubarraysWithSum(nums []int, goal int) int {
        
            hashmap := make(map[int]int)
        
            hashmap[0] = 1
        
            sum := 0
        
            count := 0
        
        
        
            for _, num := range nums {
        
                sum += num
        
                rem := sum - goal
        
                if val, ok := hashmap[rem]; ok {
        
                    count += val
        
                }
        
                hashmap[sum]++
        
            }
        
        
        
            return count
        
        }
        

        4.7.818 - 2024-03-13 19:53:19 +0300 MSK

        Find the Pivot Integer

        Code

        func getSum(x int) int {
        	return x * (x + 1) / 2
        }
        
        func pivotInteger(n int) int {
            sum := getSum(n)
        
        	l, r := 1, n
        	for l <= r {
        		m := (l + r) / 2
        		firstPart := getSum(m)
        		secondPart := sum - firstPart + m
        
        		if firstPart == secondPart {
        			return m
        		} else if firstPart > secondPart {
        			r = m - 1
        		} else {
        			l = m + 1
        		}
        	}
        
        	return -1
        }
        

        4.7.819 - 2024-03-12 19:08:41 +0300 MSK

        Remove Zero Sum Consecutive Nodes from Linked List

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func removeZeroSumSublists(head *ListNode) *ListNode {
            dummy := &ListNode{0, head}
            prefixSumToNode := make(map[int]*ListNode)
            prefixSum := 0
            for current := dummy; current != nil; current = current.Next {
                prefixSum += current.Val
                if prev, found := prefixSumToNode[prefixSum]; found {
                    toRemove := prev.Next
                    p := prefixSum
                    if toRemove != nil {
                        p += toRemove.Val
                    }
                    for toRemove != nil && p != prefixSum {
                        delete(prefixSumToNode, p)
                        toRemove = toRemove.Next
                        if toRemove != nil {
                            p += toRemove.Val
                        }
                    }
                    prev.Next = current.Next
                } else {
                    prefixSumToNode[prefixSum] = current
                }
            }
            return dummy.Next
        }
        

        4.7.820 - 2024-03-11 19:30:24 +0300 MSK

        Custom Sort String

        Code

        func customSortString(order string, s string) string {
            count := make([]int, 26)
        
            for _, c := range s {
                count[c-'a']++
            }
        
            var result strings.Builder
        
            for _, c := range order {
                result.WriteString(strings.Repeat(string(c), count[c-'a']))
                count[c-'a'] = 0
            }
        
            for i := 0; i < 26; i++ {
                result.WriteString(strings.Repeat(string('a'+i), count[i]))
            }
            // UPVOTE :)
            return result.String()
        }
        

        4.7.821 - 2024-03-10 22:58:44 +0300 MSK

        Intersection of Two Arrays

        Code

        func intersection(nums1 []int, nums2 []int) []int {
            seen := make([]int, 1000)
            for i := range nums1 {
                seen[nums1[i]]++
            }
        
            res := make([]int, 0)
            for i := range nums2 {
                if seen[nums2[i]] > 0 {
                    res = append(res, nums2[i])
                    seen[nums2[i]] = 0
                }
            }
        
            return res
        }
        

        4.7.822 - 2024-03-09 19:01:11 +0300 MSK

        Count Elements With Maximum Frequency

        Code

        func maxFrequencyElements(nums []int) int {
            mapCount := make(map[int]int)
        
            for _, val := range nums {
                mapCount[val]++
            }
        
            count := 0
            max := -1
            for _, freq := range mapCount {
                if freq > max {
                    max = freq
                }
            }
        
            for _, freq := range mapCount {
                if freq == max {
                    count += max
                }
            }
            return count
        }
        

        4.7.823 - 2024-03-09 18:59:53 +0300 MSK

        Minimum Common Value

        Code

        func getCommon(nums1 []int, nums2 []int) int {
            var l, r int
            for l < len(nums1) && r < len(nums2) {
                switch {
                case nums1[l] == nums2[r]:
                    return nums1[l]
                case nums1[l] < nums2[r]:
                    l++
                default:
                    r++
                }
            }
            return -1
        }
        

        4.7.824 - 2024-03-07 19:08:46 +0300 MSK

        Middle of the Linked List

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func middleNode(head *ListNode) *ListNode {
            if head.Next == nil {
                return head
            }
            slow, fast := head, head.Next
            move := true
            for fast.Next != nil {
                if move {
                    slow = slow.Next
                    move = false
                } else {
                    move = true
                }
                fast = fast.Next
            }
            if move {
                return slow.Next
            }
            return slow
        }
        

        4.7.825 - 2024-03-07 19:07:46 +0300 MSK

        Middle of the Linked List

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func middleNode(head *ListNode) *ListNode {
            if head.Next == nil {
                return head
            }
            slow, fast := head, head.Next
            move := true
            for fast.Next != nil {
                if move {
                    slow = slow.Next
                    move = false
                } else {
                    move = true
                }
                fast = fast.Next
            }
            if move {
                slow = slow.Next
            }
            return slow
        }
        

        4.7.826 - 2024-03-06 16:05:23 +0300 MSK

        Linked List Cycle

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func hasCycle(head *ListNode) bool {
            nodes := map[*ListNode]struct{}{}
            for head != nil {
                if _, ok := nodes[head]; ok {
                    return true
                }
                nodes[head] = struct{}{}
                head = head.Next
            }
            return false
        }
        

        4.7.827 - 2024-03-05 11:52:38 +0300 MSK

        Minimum Length of String After Deleting Similar Ends

        Code

        func minimumLength(s string) int {
            left := 0
            right := len(s) - 1
            
            for left < right {
                lc := s[left]
                rc := s[right]
                
                if lc != rc {
                    return right - left + 1
                }
                
                for left + 1 < right && lc == s[left + 1] {
                    left++
                }
                
                for left < right - 1 && rc == s[right - 1] {
                    right--
                }
                
                right--
                left++
            }
            
            return right - left + 1
        }
        

        4.7.828 - 2024-03-04 16:21:41 +0300 MSK

        Bag of Tokens

        Code

        func bagOfTokensScore(tokens []int, power int) int {
            n := len(tokens)
        	sort.Ints(tokens)
        	res := 0
        
        	l := 0
        	r := n - 1
        
        	for l <= r {
        		for l <= r && power >= tokens[l] {
        			power -= tokens[l]
        			l++
        			res++
        		}
        		
        		if res == 0 {
        			break
        		}
        
                if r - l + 1 <= 2 {
        			break
        		}
        
        		power += tokens[r]
        		r--
        		res--
        	}
        
        	return res
        }
        

        4.7.829 - 2024-03-03 10:57:46 +0300 MSK

        Remove Nth Node From End of List

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func removeNthFromEnd(head *ListNode, n int) *ListNode {
            res := &ListNode{0, head}
        
            lead := res
            for i := 0; i <= n; i++ {
                lead = lead.Next
            }
        
            cur := res
            for lead != nil {
                cur = cur.Next
                lead = lead.Next
            }
        
            cur.Next = cur.Next.Next
            return res.Next
        }
        

        4.7.830 - 2024-03-02 15:59:13 +0300 MSK

        Squares of a Sorted Array

        Code

        func sortedSquares(nums []int) []int {
            for i, num := range nums {
                if num < 0 {
                    nums[i] = -num
                } else { 
                    break
                }
            }
            slices.Sort(nums)
            for i, num := range nums {
                nums[i] = num * num
            }
            return nums
        }
        

        4.7.831 - 2024-03-02 15:57:16 +0300 MSK

        Squares of a Sorted Array

        Code

        func sortedSquares(nums []int) []int {
            for i, num := range nums {
                nums[i] = num * num
            }
            slices.Sort(nums)
            return nums
        }
        

        4.7.832 - 2024-03-02 15:56:40 +0300 MSK

        Squares of a Sorted Array

        Code

        func sortedSquares(nums []int) []int {
            for i, num := range nums {
                if num < 0 {
                    nums[i] = -num
                }
            }
            slices.Sort(nums)
            for i, num := range nums {
                nums[i] = num * num
            }
            return nums
        }
        

        4.7.833 - 2024-03-01 18:28:31 +0300 MSK

        Maximum Odd Binary Number

        Code

        func maximumOddBinaryNumber(s string) string {
        	l := len(s)
        	res := make([]byte, l)
        	index0, index1 := l-2, l-1
        	for i := 0; i < l; i++ {
        		if s[i] == '0' {
        			res[index0] = '0'
        			index0--
        		} else {
        			res[index1] = '1'
        			index1 = (index1 + 1) % l
        		}
        	}
        	return string(res)
        }
        

        4.7.834 - 2024-02-29 17:38:44 +0300 MSK

        Even Odd Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func isEvenOddTree(root *TreeNode) bool {
            q := []*TreeNode{root}
            for i:= 0; len(q) > 0; i++ {
                var prev *TreeNode
                for _, node := range q {
                    q = q[1:]
        
                    if i % 2 == 0 && node.Val % 2 != 1 {
                        return false
                    }
        
                    if i % 2 == 1 && node.Val % 2 != 0 {
                        return false
                    }
        
                    if prev != nil && i % 2 == 0 && prev.Val >= node.Val {
                        return false
                    }
        
                    if prev != nil && i % 2 == 1 && prev.Val <= node.Val {
                        return false
                    }
                   
                    prev = node
                    if node.Left != nil {
                        q = append(q, node.Left)
                    }
        
                    if node.Right != nil {
                        q = append(q, node.Right)
                    }
                }
            }
            return true
        }
        

        4.7.835 - 2024-02-28 12:31:13 +0300 MSK

        Find Bottom Left Tree Value

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func findBottomLeftValue(root *TreeNode) int {
            _, val := getBottomLeft(root)
            return val
        }
        
        func getBottomLeft(root *TreeNode) (int, int) {
            left, right := root.Left, root.Right
            if right == nil && left == nil {
                return 0, root.Val
            }
            if right == nil {
                depth, val := getBottomLeft(root.Left)
                return 1 + depth, val
            }
            if left == nil {
                depth, val := getBottomLeft(root.Right)
                return 1 + depth, val
            }
            leftDepth, leftVal := getBottomLeft(root.Left)
            rightDepth, rightVal := getBottomLeft(root.Right)
            if rightDepth > leftDepth {
                return 1 + rightDepth, rightVal
            }
            return 1 + leftDepth, leftVal
        }
        

        4.7.836 - 2024-02-27 19:25:53 +0300 MSK

        Diameter of Binary Tree

        Code

        var maxD int
        
        func diameterOfBinaryTree(root *TreeNode) int {
            maxD = 0
            find(root)
            return maxD
        }
        
        func find(root *TreeNode) int {
            if root == nil {
                return 0
            }
            left := find(root.Left)
            right := find(root.Right)
            localMax := left + right
            maxD = max(maxD, localMax)
            return max(left, right) + 1
        }
        
        func max(a, b int) int {
            if a > b {
                return a
            }
            return b
        }
        

        4.7.837 - 2024-02-26 19:57:46 +0300 MSK

        Same Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func isSameTree(p *TreeNode, q *TreeNode) bool {
            if p == nil && q == nil {
                return true
            }
            if p == nil || q == nil || p.Val != q.Val {
                return false
            }
            return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
        }
        

        4.7.838 - 2024-02-25 20:04:05 +0300 MSK

        Greatest Common Divisor Traversal

        Code

        func canTraverseAllPairs(nums []int) bool {
            if len(nums) == 1 {
                return true
            }
            n := len(nums)
            maxElement := nums[0]
            minElement := nums[0]
            for _, num := range nums {
                if num > maxElement {
                    maxElement = num
                }
                if num < minElement {
                    minElement = num
                }
            }
            if minElement == 1 {
                return false
            }
            factorArray := factorsCalculator(maxElement)
        
            parent := make([]int, maxElement+1)
            rank := make([]int, maxElement+1)
            for i := 0; i <= maxElement; i++ {
                parent[i] = i
                rank[i] = 1
            }
        
            for _, num := range nums {
                x := num
                for x > 1 {
                    p := factorArray[x]
                    union(parent, rank, p, num)
                    for x%p == 0 {
                        x = x / p
                    }
                }
            }
        
            p := find(parent, nums[0])
            for i := 1; i < n; i++ {
                if find(parent, nums[i]) != p {
                    return false
                }
            }
        
            return true
        }
        
        func factorsCalculator(n int) []int {
            dp := make([]int, n+2)
            for i := 0; i < len(dp); i++ {
                dp[i] = i
            }
            for i := 2; i <= n; i++ {
                if dp[i] == i {
                    for j := i * 2; j <= n; j += i {
                        if dp[j] == j {
                            dp[j] = i
                        }
                    }
                }
            }
            return dp
        }
        
        func find(parent []int, a int) int {
            if parent[a] == a {
                return a
            }
            parent[a] = find(parent, parent[a])
            return parent[a]
        }
        
        func union(parent []int, rank []int, a int, b int) {
            a = find(parent, a)
            b = find(parent, b)
            if a == b {
                return
            }
            if rank[a] < rank[b] {
                a, b = b, a
            }
            parent[b] = a
            rank[a] += rank[b]
        }
        

        4.7.839 - 2024-02-24 15:45:37 +0300 MSK

        Find All People With Secret

        Code

        package main
        
        import (
        	"sort"
        )
        
        func find(groups []int, index int) int {
        	for index != groups[index] {
        		index = groups[index]
        	}
        	return index
        }
        
        func findAllPeople(n int, meetings [][]int, firstPerson int) []int {
        	groups := make([]int, 100000)
        	var result []int
        	var temp []int
        
        	for i := 0; i < n; i++ {
        		groups[i] = i
        	}
        	groups[firstPerson] = 0
        
        	sort.Slice(meetings, func(i, j int) bool {
        		return meetings[i][2] < meetings[j][2]
        	})
        
        	i := 0
        	for i < len(meetings) {
        		currentTime := meetings[i][2]
        		temp = temp[:0]
        		for i < len(meetings) && meetings[i][2] == currentTime {
        			g1 := find(groups, meetings[i][0])
        			g2 := find(groups, meetings[i][1])
        			groups[max(g1, g2)] = min(g1, g2)
        			temp = append(temp, meetings[i][0], meetings[i][1])
        			i++
        		}
        		for _, j := range temp {
        			if find(groups, j) != 0 {
        				groups[j] = j
        			}
        		}
        	}
        
        	for j := 0; j < n; j++ {
        		if find(groups, j) == 0 {
        			result = append(result, j)
        		}
        	}
        
        	return result
        }
        
        func max(a, b int) int {
        	if a > b {
        		return a
        	}
        	return b
        }
        
        func min(a, b int) int {
        	if a < b {
        		return a
        	}
        	return b
        }
        

        4.7.840 - 2024-02-23 12:30:25 +0300 MSK

        Cheapest Flights Within K Stops

        Code

        type Connection struct {
        	city int
        	cost int
        }
        
        type queue []Connection
        
        func (q *queue) push(c Connection) {
        	q1 := []Connection{c}
        	*q = append(*q, q1...)
        }
        
        func (q *queue) pop() (bool, Connection) {
        
        	if q.isEmpty() {
        		return false, Connection{}
        	} else {
        		elem := (*q)[0]
        		*q = (*q)[1:]
        		return true, elem
        	}
        }
        
        func (q queue) isEmpty() bool {
        	return q.size() <= 0
        }
        
        func (q queue) size() int {
        	return len(q)
        }
        
        func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int {
        
        	minCost := math.MaxInt64
        
        	fQueue := new(queue)
        	fQueue.push(Connection{src, 0})
        
        	maxStops := k + 1
        
        	costOfFlights := make([][]int, n)
        	for i := range costOfFlights {
        		costOfFlights[i] = make([]int, n)
        	}
        
        	flightsMap := make(map[int][]int)
        	for _, v := range flights {
        		if _, ok := flightsMap[v[0]]; ok {
        			flightsMap[v[0]] = append(flightsMap[v[0]], v[1])
        		} else {
        			flightsMap[v[0]] = []int{v[1]}
        		}
        
        		costOfFlights[v[0]][v[1]] = v[2]
        	}
        
        	cityPathCost := make([]int, n) // path cost from source
        	for i := range cityPathCost {
        		cityPathCost[i] = math.MaxInt64
        	}
        
        	cityPathCost[src] = 0
        
        	for !fQueue.isEmpty() && maxStops >= 0 {
        
        		size := fQueue.size()
        		maxStops--
        
        		for size > 0 {
        			_, c := fQueue.pop()
        			size--
        
        			if c.city == dst {
        				if minCost > c.cost {
        					minCost = c.cost
        				}
        				continue
        			}
        
        			for _, v := range flightsMap[c.city] {
        
        				newCost := c.cost + costOfFlights[c.city][v]
        
        				if cityPathCost[v] > newCost {
        					fQueue.push(Connection{v, newCost})
        					cityPathCost[v] = newCost
        				}
        			}
        		}
        	}
        
        	if minCost == math.MaxInt64 {
        		minCost = -1
        	}
        
        	return minCost
        }
        

        4.7.841 - 2024-02-22 11:20:36 +0300 MSK

        Find the Town Judge

        Code

        func findJudge(n int, trust [][]int) int {
            fromTo := make([][]int, n)
            toFrom := make([][]int, n)
            for _, trustArray := range trust {
                from, to := trustArray[0], trustArray[1]
                fromTo[from-1] = append(fromTo[from-1], to)
                toFrom[to-1] = append(toFrom[to-1], from)
            }
            for i, from := range toFrom {
                if len(from) == n - 1 && len(fromTo[i]) == 0 {
                    return i + 1
                }
            }
            return -1
        }
        

        4.7.842 - 2024-02-21 11:42:07 +0300 MSK

        Bitwise AND of Numbers Range

        Code

        class Solution:
            def rangeBitwiseAnd(self, left: int, right: int) -> int:
                shift = 0
                while left != right:
                    left >>= 1
                    right >>= 1
                    shift += 1
                return left << shift
        

        4.7.843 - 2024-02-20 18:21:21 +0300 MSK

        Missing Number

        Code

        import operator
        class Solution:
            def missingNumber(self, nums: List[int]) -> int:
                return reduce(
                    operator.xor, 
                    nums, 
                    reduce(operator.xor, tuple(range(len(nums) + 1)), 0)
                )
        

        4.7.844 - 2024-02-20 18:19:05 +0300 MSK

        Missing Number

        Code

        import operator
        class Solution:
            def missingNumber(self, nums: List[int]) -> int:
                nums.extend(range(len(nums) + 1))
                return reduce(operator.xor, nums, 0)
        

        4.7.845 - 2024-02-20 18:16:37 +0300 MSK

        Missing Number

        Code

        import operator
        class Solution:
            def missingNumber(self, nums: List[int]) -> int:
                length = len(nums)
                return reduce(operator.xor, range(length), reduce(operator.xor, nums, length))
        

        4.7.846 - 2024-02-20 15:10:36 +0300 MSK

        Missing Number

        Code

        class Solution:
            def missingNumber(self, nums: List[int]) -> int:
                def xor(total: int, i: int) -> int:
                    return total ^ nums[i] ^ (i + 1)
                return reduce(xor, chain((0, ), range(len(nums))))
        

        4.7.847 - 2024-02-19 11:56:55 +0300 MSK

        Power of Two

        Code

        class Solution:
            def isPowerOfTwo(self, n: int) -> bool:
                return n > 0 and n & (n - 1) == 0
        

        4.7.848 - 2024-02-18 12:45:46 +0300 MSK

        Meeting Rooms III

        Code

        class Solution:
            def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
                unused_rooms, used_rooms = list(range(n)), []
                heapify(unused_rooms)
                meeting_count = [0] * n
                for start, end in sorted(meetings):
                    while used_rooms and used_rooms[0][0] <= start:
                        _, room = heappop(used_rooms)
                        heappush(unused_rooms, room)
                    if unused_rooms:
                        room = heappop(unused_rooms)
                        heappush(used_rooms, [end, room])
                    else:
                        room_availability_time, room = heappop(used_rooms)
                        heappush(
                            used_rooms,
                            [room_availability_time + end - start, room]
                        )
                    meeting_count[room] += 1
                return meeting_count.index(max(meeting_count))
        

        4.7.849 - 2024-02-17 15:07:38 +0300 MSK

        Furthest Building You Can Reach

        Code

        class Solution:
            def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
                heap = []
                i = 0
                length = len(heights)
                for i in range(length - 1):
                    diff = heights[i + 1] - heights[i]           
                    if diff <= 0:
                        continue
                    bricks -= diff
                    heapq.heappush(heap, -diff)
                    if bricks < 0:
                        bricks += -heapq.heappop(heap)
                        ladders -= 1
                    if ladders < 0:
                        return i
                return length - 1
          
        

        4.7.850 - 2024-02-17 15:03:52 +0300 MSK

        Furthest Building You Can Reach

        Code

        class Solution:
           def furthestBuilding(self, h: List[int], b: int, l: int) -> int:
               p = []
               
               i = 0
               for i in range(len(h) - 1):
                   diff = h[i + 1] - h[i]
                   
                   if diff <= 0:
                       continue
                   
                   b -= diff
                   x = heapq.heappush(p, -diff)
                   print(x)
                   if b < 0:
                       b += -heapq.heappop(p)
                       l -= 1
                       
                   if l < 0:
                       return i
               return len(h)-1
          
        

        4.7.851 - 2024-02-16 18:29:09 +0300 MSK

        Least Number of Unique Integers after K Removals

        Code

        class Solution:
            def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
                counter = defaultdict(int)
                for num in arr:
                    counter[num] += 1
                nums = [(count, num) for num, count in counter.items()]
                nums.sort()
                removed = 0
                for count, num in nums:
                    if k < count:
                        break
                    k -= count
                    removed += 1
                return len(counter) - removed
        

        4.7.852 - 2024-02-15 12:51:25 +0300 MSK

        Find Polygon With the Largest Perimeter

        Code

        class Solution:
            def largestPerimeter(self, nums: List[int]) -> int:
                nums.sort()
                previous_elements_sum = 0
                ans = -1
                for num in nums:
                    if num < previous_elements_sum:
                        ans = num + previous_elements_sum
                    previous_elements_sum += num
                return ans
        

        4.7.853 - 2024-02-14 10:48:17 +0300 MSK

        Rearrange Array Elements by Sign

        Code

        class Solution:
            def rearrangeArray(self, nums: List[int]) -> List[int]:
                res = []
                pos, neg = [], []
                length = len(nums)
                for i in range(length):
                    num = nums[i]
                    if num > 0:
                        pos.append(num)
                    else:
                        neg.append(num)
                pos.reverse()
                neg.reverse()
                while pos and neg:
                    res.extend((pos.pop(), neg.pop()))
                return res
        

        4.7.854 - 2024-02-13 16:10:55 +0300 MSK

        Find First Palindromic String in the Array

        Code

        class Solution:
            def firstPalindrome(self, words: List[str]) -> str:
                for s in words:
                    for i in range(len(s) // 2):
                        if s[i] != s[-i - 1]:
                            break
                    else:
                        return s
                return ""
        

        4.7.855 - 2024-02-12 12:50:44 +0300 MSK

        Majority Element

        Code

        class Solution:
            def majorityElement(self, nums: List[int]) -> int:
                counter = defaultdict(int)
                half = len(nums) // 2
                for num in nums:
                    counter[num] += 1
                    if counter[num] > half:
                        return num
                raise Exception()
        

        4.7.856 - 2024-02-11 16:20:27 +0300 MSK

        Cherry Pickup II

        Code

        class Solution:
            def cherryPickup(self, grid: List[List[int]]) -> int:
                n = len(grid)
                m = len(grid[0])
        
                # Create 3D DP table with initial values of 0
                dp = [[[0] * m for _ in range(m)] for _ in range(n)]
        
                # Set the starting point value (top-left and top-right corner)
                cherries = 0
                dp[0][0][m - 1] = grid[0][0] + grid[0][m - 1]
        
                # Iterate through each row from second onwards
                for i in range(1, n):
                    # Iterate through each column for robot 1
                    for j in range(m):
                        # Iterate through each column for robot 2
                        for k in range(m):
                            # Skip invalid states:
                            # - Both robots in the same row (j > i)
                            # - Robot 2 left of robot 1 (k < m - i - 1)
                            # - Robot 1 further right than robot 2 (j > k)
                            if j > i or k < m - i - 1 or j > k:
                                continue
                            # Base case: no moves possible, use previous state
                            dp[i][j][k] = dp[i - 1][j][k]
                            # Explore moves for robot 1:
                            # - Up-diagonal with robot 2 at same position
                            if j - 1 >= 0:
                                dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - 1][k])
                            # - Up-diagonal with robot 2 one step left/right
                            if j - 1 >= 0 and k - 1 >= 0:
                                dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - 1][k - 1])
                            if j - 1 >= 0 and k + 1 < m:
                                dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - 1][k + 1])
                            # Explore moves for robot 2:
                            # - Up-diagonal with robot 1 at same position
                            if j + 1 < m:
                                dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j + 1][k])
                            # - Up-diagonal with robot 1 one step left/right
                            if j + 1 < m and k - 1 >= 0:
                                dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j + 1][k - 1])
                            if j + 1 < m and k + 1 < m:
                                dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j + 1][k + 1])
                            # Explore horizontal moves for both robots:
                            # - Both robots move left
                            if k - 1 >= 0:
                                dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j][k - 1])
                            # - Both robots move right
                            if k + 1 < m:
                                dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j][k + 1])
                            # Add cherries only if robots are in different positions
                            if j != k:
                                dp[i][j][k] += grid[i][j] + grid[i][k]
                            else:
                                dp[i][j][k] += grid[i][j]  # Only one robot picks if they land in the same cell
                            # Update maximum cherries collected so far
                            cherries = max(cherries, dp[i][j][k])
        
                return cherries
        

        4.7.857 - 2024-02-10 15:12:54 +0300 MSK

        Palindromic Substrings

        Code

        class Solution:
            def countSubstrings(self, s: str) -> int:
                n = len(s)
                palindrome = [[False] * n for _ in range(n)]
                ans = 0
        
                for i in range(n):
                    palindrome[i][i] = True
                    ans += 1
        
                for i in range(n - 1):
                    if s[i] == s[i + 1]:
                        palindrome[i][i + 1] = True
                        ans += 1
        
                for length in range(3, n + 1):
                    for i in range(n - length + 1):
                        if s[i] == s[i + length - 1] and palindrome[i + 1][i + length - 2]:
                            palindrome[i][i + length - 1] = True
                            ans += 1
        
                return ans
        

        4.7.858 - 2024-02-09 19:12:32 +0300 MSK

        Largest Divisible Subset

        Code

        class Solution:
            def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
                nums.sort()
                n = len(nums)
                dp = [1] * n
                max_size, max_index = 1, 0
        
                for i in range(1, n):
                    for j in range(i):
                        if nums[i] % nums[j] == 0:
                            dp[i] = max(dp[i], dp[j] + 1)
                            if dp[i] > max_size:
                                max_size = dp[i]
                                max_index = i
        
                result = []
                num = nums[max_index]
                for i in range(max_index, -1, -1):
                    if num % nums[i] == 0 and dp[i] == max_size:
                        result.append(nums[i])
                        num = nums[i]
                        max_size -= 1
        
                return result
        

        4.7.859 - 2024-02-08 15:50:03 +0300 MSK

        Perfect Squares

        Code

        class Solution:
            def numSquares(self, n: int) -> int:
                dp = [float('inf')] * (n + 1)
                dp[0] = 0
                for i in range(1, n + 1):
                    min_val = float('inf')
                    j = 1
                    while j * j <= i:
                        min_val = min(min_val, dp[i - j * j] + 1)
                        j += 1
                    dp[i] = min_val
                return dp[n]
        

        4.7.860 - 2024-02-07 10:59:44 +0300 MSK

        Sort Characters By Frequency

        Code

        class Solution:
            def frequencySort(self, s: str) -> str:
                counter = defaultdict(int)
                for char in s:
                    counter[char] += 1
                pq = [(-freq, char) for char, freq in counter.items()]
                heapq.heapify(pq)
                result = []
                while pq:
                    freq, char = heapq.heappop(pq)
                    result.append(char * -freq)
                return "".join(result)
        

        4.7.861 - 2024-02-07 10:54:21 +0300 MSK

        Sort Characters By Frequency

        Code

        class Solution:
            def frequencySort(self, s: str) -> str:
                counter = {}
                for char in s:
                    if char not in counter:
                        counter[char] = -ord(char)
                    counter[char] -= 100
                return "".join(sorted(s, key=lambda val: counter[val]))
        

        4.7.862 - 2024-02-07 10:52:55 +0300 MSK

        Sort Characters By Frequency

        Code

        class Solution:
            def frequencySort(self, s: str) -> str:
                counter = {}
                for char in s:
                    if char not in counter:
                        counter[char] = ord(char)
                    counter[char] += 100
                return "".join(sorted(s, key=lambda val: -counter[val]))
        

        4.7.863 - 2024-02-07 10:49:08 +0300 MSK

        Sort Characters By Frequency

        Code

        class Solution:
            def frequencySort(self, s: str) -> str:
                counter = defaultdict(int)
                for char in s:
                    counter[char] += 1
                return "".join(sorted(s, key=lambda val: -(ord(val) + counter[val] * 100)))
        

        4.7.864 - 2024-02-06 09:02:52 +0300 MSK

        Group Anagrams

        Code

        class Solution:
            def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
                anagrams = defaultdict(list)
                for anagram in strs:
                    anagrams[tuple(sorted(anagram))].append(anagram)
                return anagrams.values()
        

        4.7.865 - 2024-02-05 10:12:58 +0300 MSK

        First Unique Character in a String

        Code

        class Solution:
            def firstUniqChar(self, s: str) -> int:
                counter = [0] * 26
        
                for char in s:
                    idx = ord(char) - ord('a')
                    if counter[idx] in (0, 1):
                        counter[idx] += 1
                for i in range(len(s)):
                    if counter[ord(s[i]) - ord('a')] == 1:
                        return i
                return -1
        

        4.7.866 - 2024-02-04 15:38:07 +0300 MSK

        Partition Array for Maximum Sum

        Code

        class Solution:
            def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
                min_num = -1
                length = len(arr)
                last_idx = length - 1
                cache = [-1] * length
        
                def dp(start: int) -> int:
                    cached = cache[start]
                    if cached != -1:
                        return cached
                    max_num = min_num
                    max_sum = 0
                    for i in range(start, min(start + k, length)):
                        max_num = max(max_num, arr[i])
                        cur_sum = max_num * (i - start + 1)
                        if i != last_idx:
                            cur_sum += dp(i + 1)
                        max_sum = max(max_sum, cur_sum)
                    cache[start] = max_sum
                    return max_sum
                
                return dp(0)
                    
        

        4.7.867 - 2024-02-04 15:17:08 +0300 MSK

        Minimum Window Substring

        Code

        class Solution:
            def minWindow(self, s: str, t: str) -> str:
                if not s or not t:
                    return ""
        
                dictT = defaultdict(int)
                for c in t:
                    dictT[c] += 1
        
                required = len(dictT)
                l, r = 0, 0
                formed = 0
        
                windowCounts = defaultdict(int)
                ans = [-1, 0, 0]
        
                while r < len(s):
                    c = s[r]
                    windowCounts[c] += 1
        
                    if c in dictT and windowCounts[c] == dictT[c]:
                        formed += 1
        
                    while l <= r and formed == required:
                        c = s[l]
        
                        if ans[0] == -1 or r - l + 1 < ans[0]:
                            ans[0] = r - l + 1
                            ans[1] = l
                            ans[2] = r
        
                        windowCounts[c] -= 1
                        if c in dictT and windowCounts[c] < dictT[c]:
                            formed -= 1
        
                        l += 1
        
                    r += 1
        
                return "" if ans[0] == -1 else s[ans[1]:ans[2] + 1]
        

        4.7.868 - 2024-02-02 19:53:06 +0300 MSK

        Divide Array Into Arrays With Max Difference

        Code

        class Solution:
            def divideArray(self, nums, k):
                size = len(nums)
                if size % 3 != 0:
                    return []
        
                nums.sort()
        
                result = []
                group_index = 0
                for i in range(0, size, 3):
                    if i + 2 < size and nums[i + 2] - nums[i] <= k:
                        result.append([nums[i], nums[i + 1], nums[i + 2]])
                        group_index += 1
                    else:
                        return []
                return result
        

        4.7.869 - 2024-02-02 19:52:11 +0300 MSK

        Divide Array Into Arrays With Max Difference

        Code

        class Solution:
            def divideArray(self, nums, k):
                size = len(nums)
                if size % 3 != 0:
                    return []
        
                nums.sort()
        
                result = []
                group_index = 0
                for i in range(0, size, 3):
                    if i + 2 < size and nums[i + 2] - nums[i] <= k:
                        result.append([nums[i], nums[i + 1], nums[i + 2]])
                        group_index += 1
                    else:
                        return []
                return result
        

        4.7.870 - 2024-02-02 19:51:07 +0300 MSK

        Sequential Digits

        Code

        class Solution:
            def sequentialDigits(self, low, high):
                a = []
        
                for i in range(1, 10):
                    num = i
                    next_digit = i + 1
        
                    while num <= high and next_digit <= 9:
                        num = num * 10 + next_digit
                        if low <= num <= high:
                            a.append(num)
                        next_digit += 1
        
                a.sort()
                return a
        

        4.7.871 - 2024-01-31 11:09:51 +0300 MSK

        Daily Temperatures

        Code

        class Solution:
            def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
                temps_left = defaultdict(list)
                to_pop = []
                length = len(temperatures)
                ans = [0] * length
                for i in range(length):
                    temp = temperatures[i]
                    for temp_left, ids in temps_left.items():
                        if temp <= temp_left:
                            continue
                        for id in ids:
                            ans[id] = i - id
                        to_pop.append(temp_left)
                    temps_left[temp].append(i)
                    for temp in to_pop:
                        temps_left.pop(temp)
                    to_pop.clear()
                
                return ans
        

        4.7.872 - 2024-01-30 15:36:53 +0300 MSK

        Evaluate Reverse Polish Notation

        Code

        class Solution:
            def evalRPN(self, tokens: List[str]) -> int:
                stack: list[int] = []
                for token in tokens:
                    match token:
                        case "+":
                            stack.append(stack.pop() + stack.pop())
                        case "-":
                            last, prev = stack.pop(), stack.pop()
                            stack.append(prev - last)
                        case "*":
                            stack.append(stack.pop() * stack.pop())
                        case "/": 
                            last, prev = stack.pop(), stack.pop()
                            stack.append(int(prev / last))
                        case _:
                            stack.append(int(token))
                return stack[0]
        

        4.7.873 - 2024-01-29 09:44:33 +0300 MSK

        Implement Queue using Stacks

        Code

        class MyQueue:
        
            def __init__(self):
                self.stack_in = []
                self.stack_out = []
        
            def push(self, x: int) -> None:
                self.stack_in.append(x)
        
            def pop(self) -> int:
                self.peek()
                return self.stack_out.pop()
        
            def peek(self) -> int:
                if self.stack_out:
                    return self.stack_out[-1]
                
                while self.stack_in:
                    self.stack_out.append(self.stack_in.pop())
        
                return self.stack_out[-1]
        
            def empty(self) -> bool:
                return not self.stack_out and not self.stack_in
        
        
        # Your MyQueue object will be instantiated and called as such:
        # obj = MyQueue()
        # obj.push(x)
        # param_2 = obj.pop()
        # param_3 = obj.peek()
        # param_4 = obj.empty()
        

        4.7.874 - 2024-01-28 13:34:03 +0300 MSK

        Number of Submatrices That Sum to Target

        Code

        class Solution:
            def numSubmatrixSumTarget(self, matrix, target):
                m, n = len(matrix), len(matrix[0])
        
                for row in range(m):
                    for col in range(1, n):
                        matrix[row][col] += matrix[row][col - 1]
        
                count = 0
        
                for c1 in range(n):
                    for c2 in range(c1, n):
                        prefix_sum_count = {0: 1}
                        sum_val = 0
        
                        for row in range(m):
                            sum_val += matrix[row][c2] - (matrix[row][c1 - 1] if c1 > 0 else 0)
                            count += prefix_sum_count.get(sum_val - target, 0)
                            prefix_sum_count[sum_val] = prefix_sum_count.get(sum_val, 0) + 1
        
                return count
        

        4.7.875 - 2024-01-27 10:05:52 +0300 MSK

        K Inverse Pairs Array

        Code

        class Solution:
            def kInversePairs(self, n: int, k: int) -> int:
                MOD = 10**9 + 7
                dp = [[0] * (k + 1) for _ in range(n + 1)]
        
                for i in range(1, n + 1):
                    for j in range(k + 1):
                        if j == 0:
                            dp[i][j] = 1
                        else:
                            val = (dp[i - 1][j] + MOD - (dp[i - 1][j - i] if j - i >= 0 else 0)) % MOD
                            dp[i][j] = (dp[i][j - 1] + val) % MOD
        
                return (dp[n][k] + MOD - (dp[n][k - 1] if k > 0 else 0)) % MOD
        

        4.7.876 - 2024-01-26 11:02:15 +0300 MSK

        Out of Boundary Paths

        Code

        class Solution:
        
            def findPaths(self, m: int, n: int, N: int, x: int, y: int) -> int:
        
                M = 1000000000 + 7
        
                dp = [[0] * n for _ in range(m)]
        
                dp[x][y] = 1
        
                count = 0
        
        
        
                for moves in range(1, N + 1):
        
                    temp = [[0] * n for _ in range(m)]
        
        
        
                    for i in range(m):
        
                        for j in range(n):
        
                            if i == m - 1:
        
                                count = (count + dp[i][j]) % M
        
                            if j == n - 1:
        
                                count = (count + dp[i][j]) % M
        
                            if i == 0:
        
                                count = (count + dp[i][j]) % M
        
                            if j == 0:
        
                                count = (count + dp[i][j]) % M
        
                            temp[i][j] = (
        
                                ((dp[i - 1][j] if i > 0 else 0) + (dp[i + 1][j] if i < m - 1 else 0)) % M +
        
                                ((dp[i][j - 1] if j > 0 else 0) + (dp[i][j + 1] if j < n - 1 else 0)) % M
        
                            ) % M
        
        
        
                    dp = temp
        
        
        
                return count
        

        4.7.877 - 2024-01-25 17:31:23 +0300 MSK

        Longest Common Subsequence

        Code

        class Solution:
            def longestCommonSubsequence(self, text1: str, text2: str) -> int:
                # Get the lengths of both input strings
                len_text1, len_text2 = len(text1), len(text2)
              
                # Initialize a 2D array (list of lists) with zeros for dynamic programming
                # The array has (len_text1 + 1) rows and (len_text2 + 1) columns
                dp_matrix = [[0] * (len_text2 + 1) for _ in range(len_text1 + 1)]
              
                # Loop through each character index of text1 and text2
                for i in range(1, len_text1 + 1):
                    for j in range(1, len_text2 + 1):
                        # If the characters match, take the diagonal value and add 1
                        if text1[i - 1] == text2[j - 1]:
                            dp_matrix[i][j] = dp_matrix[i - 1][j - 1] + 1
                        else:
                            # If the characters do not match, take the maximum of the value from the left and above
                            dp_matrix[i][j] = max(dp_matrix[i - 1][j], dp_matrix[i][j - 1])
              
                # The bottom-right value in the matrix contains the length of the longest common subsequence
                return dp_matrix[len_text1][len_text2]
        

        4.7.878 - 2024-01-24 10:39:27 +0300 MSK

        Pseudo-Palindromic Paths in a Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:
                if not root:
                    return 0
                
                num_count = defaultdict(int)
                perm_count = 0
        
                def traverse(node: TreeNode) -> int:
                    val, left, right = node.val, node.left, node.right
                    num_count[val] += 1
                    res = 0
                    if not left and not right:
                        non_even = 0
                        for num in num_count.values():
                            if num % 2 == 0:
                                continue
                            if non_even == 1:
                                break
                            non_even += 1
                        else:
                            res += 1
                    if left:
                        res += traverse(left)
                    if right: 
                        res += traverse(right)
                    num_count[val] = max(0, num_count[val] - 1)
                    return res 
        
                return traverse(root)
        

        4.7.879 - 2024-01-24 10:27:08 +0300 MSK

        Pseudo-Palindromic Paths in a Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:
                if not root:
                    return 0
                
                num_count = defaultdict(int)
                perm_count = 0
        
                def traverse(node: TreeNode) -> int:
                    if not node:
                        return 0
                    val, left, right = node.val, node.left, node.right
                    num_count[val] += 1
                    res = 0
                    if not left and not right:
                        non_even = 0
                        for num in num_count.values():
                            if num % 2 == 0:
                                continue
                            non_even += 1
                            if non_even > 1:
                                break
                        else:
                            res += 1
                    res += traverse(left) + traverse(right)
                    num_count[val] = max(0, num_count[val] - 1)
                    return res 
        
                return traverse(root)
        

        4.7.880 - 2024-01-23 10:54:38 +0300 MSK

        Maximum Length of a Concatenated String with Unique Characters

        Code

        class Solution:
            def maxLength(self, arr: List[str]) -> int:
                cur = set()
                length = len(arr)
                max_length = 0
        
                def backtrack(start: int) -> None:
                    nonlocal max_length 
                    
                    for i in range(start, length):
                        new_subs = arr[i]
                        new = set(new_subs)
                        if len(new_subs) != len(new) or len(cur.intersection(new)) != 0:
                            continue
                        cur.update(new)
                        backtrack(i + 1)
                        cur.difference_update(new)
        
                    max_length = max(max_length, len(cur))
        
                backtrack(0)
        
                return max_length
        

        4.7.881 - 2024-01-22 12:39:06 +0300 MSK

        Set Mismatch

        Code

        class Solution:
            def findErrorNums(self, nums: List[int]) -> List[int]:
                length = len(nums)
                # dupl_xor_miss = duplicate ^ missing
                dupl_xor_miss = reduce(lambda total, i: total ^ i ^ nums[i - 1], range(length + 1))
                rightmost_set_bit = dupl_xor_miss & -dupl_xor_miss
                xor_group1 = xor_group2 = 0
                for i in range(1, length + 1):
                    if i & rightmost_set_bit:
                        xor_group1 ^= i
                    else:
                        xor_group2 ^= i
                    if nums[i - 1] & rightmost_set_bit:
                        xor_group1 ^= nums[i - 1]
                    else:
                        xor_group2 ^= nums[i - 1]
                for num in nums:
                    if num == xor_group1:
                        return num, xor_group2
                    if num == xor_group2:
                        return num, xor_group1 
                
                raise Exception()
        

        4.7.882 - 2024-01-21 21:12:22 +0300 MSK

        House Robber

        Code

        class Solution:
            def rob(self, nums: List[int]) -> int:
                length = len(nums)
                cache = {}
        
                def dp(i: int) -> int:
                    if i >= length:
                        return 0
                    val = nums[i]
                    if i in cache:
                        return cache[i]
                    res = max(dp(i + 1), val + dp(i + 2))
                    cache[i] = res
                    return res 
        
                return dp(0)
        

        4.7.883 - 2024-01-20 17:21:44 +0300 MSK

        Sum of Subarray Minimums

        Code

        class Solution:
            def sumSubarrayMins(self, arr: List[int]) -> int:
                n = len(arr)
                left = [-1] * n 
                right = [n] * n
                stack = []
        
                for i, value in enumerate(arr):
                    while stack and arr[stack[-1]] >= value:  
                        stack.pop()  
                    if stack:
                        left[i] = stack[-1]  
                    stack.append(i) 
        
                stack = [] 
        
                
                for i in range(n - 1, -1, -1):  
                    while stack and arr[stack[-1]] > arr[i]: 
                        stack.pop()  
                    if stack:
                        right[i] = stack[-1]  
                    stack.append(i) 
        
                mod = 10**9 + 7 
        
                result = sum((i - left[i]) * (right[i] - i) * value for i, value in enumerate(arr)) % mod
              
                return result 
        

        4.7.884 - 2024-01-19 11:46:22 +0300 MSK

        Minimum Falling Path Sum

        Code

        class Solution:
            def minFallingPathSum(self, matrix: List[List[int]]) -> int:
                length = len(matrix)
                cache = {}
                deltas = ((1, 0), (1, 1), (1, -1))
                last_row = length - 1
        
                def dp(row: int, col: int) -> int:
                    if (row, col) in cache:
                        return cache[(row, col)]
                    val = matrix[row][col]
                    if row == last_row:
                        return val
                    min_cost = None
                    for delta_row, delta_col in deltas:
                        new_row, new_col = row + delta_row, col + delta_col
                        if new_col == length or new_col == -1:
                            continue
                        cost = dp(new_row, new_col)
                        min_cost = cost if min_cost is None else min(min_cost, cost)
                    res = val + min_cost
                    cache[(row, col)] = res
                    return res
        
                return min(dp(0, col) for col in range(length))
        

        4.7.885 - 2024-01-19 11:45:33 +0300 MSK

        Minimum Falling Path Sum

        Code

        class Solution:
            def minFallingPathSum(self, matrix: List[List[int]]) -> int:
                length = len(matrix)
                max_val = 101 * length * length
                cache = {}
                deltas = ((1, 0), (1, 1), (1, -1))
                last_row = length - 1
        
                def dp(row: int, col: int) -> int:
                    if (row, col) in cache:
                        return cache[(row, col)]
                    val = matrix[row][col]
                    if row == last_row:
                        return val
                    min_cost = max_val
                    for delta_row, delta_col in deltas:
                        new_row, new_col = row + delta_row, col + delta_col
                        if new_col == length or new_col == -1:
                            continue
                        cost = dp(new_row, new_col)
                        min_cost = min(min_cost, cost)
                    res = val + min_cost
                    cache[(row, col)] = res
                    return res
        
                return min(dp(0, col) for col in range(length))
        

        4.7.886 - 2024-01-18 13:27:10 +0300 MSK

        Climbing Stairs

        Code

        class Solution:
            def climbStairs(self, n: int) -> int:
                prev, cur = 1, 2
                if n == prev:
                    return prev
                if n == cur:
                    return cur
                for i in range(2, n):
                    new = prev + cur
                    cur, prev = new, cur
                return cur
        

        4.7.887 - 2024-01-17 19:14:04 +0300 MSK

        Unique Number of Occurrences

        Code

        class Solution:
            def uniqueOccurrences(self, arr: List[int]) -> bool:
                counts = defaultdict(int)
                for num in arr:
                    counts[num] += 1
        
                viewed = set()
                for _, count in counts.items():
                    if count in viewed:
                        return False
                    viewed.add(count)
                return True
        

        4.7.888 - 2024-01-16 11:04:01 +0300 MSK

        Insert Delete GetRandom O(1)

        Code

        import random
        
        class RandomizedSet:
        
            def __init__(self):
                self._nums_map = {}
                self._nums = []
                
        
            def insert(self, val: int) -> bool:
                if val in self._nums_map:
                    return False
                self._nums_map[val] = len(self._nums)
                self._nums.append(val)
                return True
        
            def remove(self, val: int) -> bool:
                if val not in self._nums_map:
                    return False
                last = self._nums[-1]
                idx = self._nums_map[val]
                self._nums_map[last] = idx
                self._nums[idx] = last
                self._nums.pop()
                self._nums_map.pop(val)
                return True
                
            def getRandom(self) -> int:
                return random.choice(self._nums) 
        
        
        # Your RandomizedSet object will be instantiated and called as such:
        # obj = RandomizedSet()
        # param_1 = obj.insert(val)
        # param_2 = obj.remove(val)
        # param_3 = obj.getRandom()
        

        4.7.889 - 2024-01-15 11:45:13 +0300 MSK

        Find Players With Zero or One Losses

        Code

        class Solution:
            def findWinners(self, matches):
                losses = [0] * 100001
        
                for winner, loser in matches:
                    if losses[winner] == 0:
                        losses[winner] = -1
        
                    if losses[loser] == -1:
                        losses[loser] = 1
                    else:
                        losses[loser] += 1
        
                zero_loss = [i for i in range(1, 100001) if losses[i] == -1]
                one_loss = [i for i in range(1, 100001) if losses[i] == 1]
        
                return [zero_loss, one_loss]
        

        4.7.890 - 2024-01-14 17:27:29 +0300 MSK

        Determine if Two Strings Are Close

        Code

        
        class Solution:
            def closeStrings(self, word1: str, word2: str) -> bool:
                freq1 = [0] * 26
                freq2 = [0] * 26
        
                for ch in word1:
                    freq1[ord(ch) - ord('a')] += 1
        
                for ch in word2:
                    freq2[ord(ch) - ord('a')] += 1
        
                for i in range(26):
                    if (freq1[i] == 0 and freq2[i] != 0) or (freq1[i] != 0 and freq2[i] == 0):
                        return False
        
                freq1.sort()
                freq2.sort()
        
                for i in range(26):
                    if freq1[i] != freq2[i]:
                        return False
        
                return True
        

        4.7.891 - 2024-01-13 17:33:48 +0300 MSK

        Minimum Number of Steps to Make Two Strings Anagram

        Code

        class Solution:
            def minSteps(self, s: str, t: str) -> int:
                count_s = [0] * 26
                count_t = [0] * 26
        
                for char in s:
                    count_s[ord(char) - ord('a')] += 1
        
                for char in t:
                    count_t[ord(char) - ord('a')] += 1
        
                steps = 0
                for i in range(26):
                    steps += abs(count_s[i] - count_t[i])
        
                return steps // 2
        

        4.7.892 - 2024-01-12 23:55:40 +0300 MSK

        Determine if String Halves Are Alike

        Code

        class Solution:
            def halvesAreAlike(self, s: str) -> bool:
                def count_vowels(string):
                    vowels = set('aeiouAEIOU')
                    return sum(1 for char in string if char in vowels)
        
                length = len(s)
                mid_point = length // 2
        
                first_half = s[:mid_point]
                second_half = s[mid_point:]
        
                return count_vowels(first_half) == count_vowels(second_half)
        

        4.7.893 - 2024-01-11 12:15:51 +0300 MSK

        Maximum Difference Between Node and Ancestor

        Code

        # Definition for a binary tree node.
        # class TreeNode(object):
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution(object):
            def maxAncestorDiff(self, root):
                if not root:
                    return 0
                self.diff = 0
                self.helper(root, root.val, root.val)
                return self.diff
            
            def helper(self, root, min_val, max_val):
                if not root:
                    return
                self.diff = max(self.diff, max(abs(min_val - root.val), abs(max_val - root.val)))
                min_val = min(min_val, root.val)
                max_val = max(max_val, root.val)
                self.helper(root.left, min_val, max_val)
                self.helper(root.right, min_val, max_val)
                
        

        4.7.894 - 2024-01-10 11:34:26 +0300 MSK

        Amount of Time for Binary Tree to Be Infected

        Code

        class Solution:
            def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
                def dfs(node):
                    if node is None:
                        return
                    if node.left:
                        graph[node.val].append(node.left.val)
                        graph[node.left.val].append(node.val)
                    if node.right:
                        graph[node.val].append(node.right.val)
                        graph[node.right.val].append(node.val)
                    dfs(node.left)
                    dfs(node.right)
        
                graph = defaultdict(list)
                dfs(root)
                visited = set()
                queue = deque([start])
                time = -1
                while queue:
                    time += 1
                    for _ in range(len(queue)):
                        current_node = queue.popleft()
                        visited.add(current_node)
                        for neighbor in graph[current_node]:
                            if neighbor not in visited:
                                queue.append(neighbor)
                return time
        

        4.7.895 - 2024-01-09 19:45:41 +0300 MSK

        Leaf-Similar Trees

        Code

        class Solution:
            def leafSimilar(self, root1, root2):
                def dfs(node):
                    if node:
                        if not node.left and not node.right:
                            yield node.val
                        yield from dfs(node.left)
                        yield from dfs(node.right)
        
                return list(dfs(root1)) == list(dfs(root2))
        

        4.7.896 - 2024-01-08 17:44:21 +0300 MSK

        Range Sum of BST

        Code

        class Solution:
            def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
                def dfs(node):
                    if not node:
                        return 0
                    
                    current_val = 0
                    if low <= node.val <= high:
                        current_val = node.val
                    
                    left_sum = dfs(node.left)
                    right_sum = dfs(node.right)
                    
                    return current_val + left_sum + right_sum
                
                return dfs(root)
        

        4.7.897 - 2024-01-07 12:26:09 +0300 MSK

        Maximum Profit in Job Scheduling

        Code

        class Solution:
            def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
                jobs = sorted(zip(endTime, startTime, profit))
              
                number_of_jobs = len(profit)
              
                dp = [0] * (number_of_jobs + 1)
              
                for i, (current_end_time, current_start_time, current_profit) in enumerate(jobs):
                    index = bisect_right(jobs, current_start_time, hi=i, key=lambda x: x[0])
                    dp[i + 1] = max(dp[i], dp[index] + current_profit)
              
                return dp[number_of_jobs]
        

        4.7.898 - 2024-01-07 12:23:04 +0300 MSK

        Arithmetic Slices II - Subsequence

        Code

        class Solution:
            def numberOfArithmeticSlices(self, nums: List[int]) -> int:
                n = len(nums)
                total_count = 0  
                dp = [defaultdict(int) for _ in range(n)]
        
                for i in range(1, n):
                    for j in range(i):
                        diff = nums[i] - nums[j]
                        dp[i][diff] += 1  
                        if diff in dp[j]:
                            dp[i][diff] += dp[j][diff]
                            total_count += dp[j][diff]
        
                return total_count
        

        4.7.899 - 2024-01-05 13:00:49 +0300 MSK

        Longest Increasing Subsequence

        Code

        class Solution:
            def lengthOfLIS(self, nums: List[int]) -> int:
                if not nums:
                    return 0
        
                n = len(nums)
                dp = [1] * n
        
                for i in range(1, n):
                    for j in range(i):
                        if nums[i] > nums[j]:
                            dp[i] = max(dp[i], dp[j] + 1)
        
                return max(dp)
        

        4.7.900 - 2024-01-04 14:11:50 +0300 MSK

        Minimum Number of Operations to Make Array Empty

        Code

        class Solution:
            def minOperations(self, nums: List[int]) -> int:
                counter = Counter(nums)
                ans = 0
                for c in counter.values():
                    if c == 1: 
                        return -1
                    ans += ceil(c / 3)
                return ans
        

        4.7.901 - 2024-01-03 14:46:50 +0300 MSK

        Number of Laser Beams in a Bank

        Code

        class Solution:
            def numberOfBeams(self, bank):
                ans, temp = 0, 0
                for s in bank:
                    n = s.count('1')
                    if n == 0:
                        continue
                    ans += temp * n
                    temp = n
                return ans
        

        4.7.902 - 2024-01-02 15:20:19 +0300 MSK

        Convert an Array Into a 2D Array With Conditions

        Code

        class Solution:
            def findMatrix(self, v: List[int]) -> List[List[int]]:
                um = {}
                for i in v:
                    um[i] = um.get(i, 0) + 1
                
                ans = []
                while um:
                    temp = []
                    to_erase = []
                    for f, s in um.items():
                        temp.append(f)
                        s -= 1
                        if s == 0:
                            to_erase.append(f)
                        um[f] = s
                    ans.append(temp)
                    for i in to_erase:
                        del um[i]
                return ans
        

        4.7.903 - 2024-01-01 16:10:42 +0300 MSK

        Assign Cookies

        Code

        class Solution:
            def findContentChildren(self, g: List[int], s: List[int]) -> int:
                g.sort()
                s.sort()
                content_children = 0
                cookie_index = 0
                while cookie_index < len(s) and content_children < len(g):
                    if s[cookie_index] >= g[content_children]:
                        content_children += 1
                    cookie_index += 1
                return content_children
        

        4.7.904 - 2023-12-31 13:19:35 +0300 MSK

        Largest Substring Between Two Equal Characters

        Code

        class Solution:
            def maxLengthBetweenEqualCharacters(self, s: str) -> int:
                ans = -1
                
                for left in range(len(s)):
                    for right in range(left + 1, len(s)):
                        if s[left] == s[right]:
                            ans = max(ans, right - left - 1)
                
                return ans
        

        4.7.905 - 2023-12-30 14:22:38 +0300 MSK

        Redistribute Characters to Make All Strings Equal

        Code

        class Solution:
            def makeEqual(self, words: List[str]) -> bool:
                counts = defaultdict(int)
                for word in words:
                    for c in word:
                        counts[c] += 1
                
                n = len(words)
                for val in counts.values():
                    if val % n != 0:
                        return False
                
                return True
        

        4.7.906 - 2023-12-29 10:09:26 +0300 MSK

        Minimum Difficulty of a Job Schedule

        Code

        class Solution:
            def minDifficulty(self, jobDifficulty, days):
                length = len(jobDifficulty)
                if days > length:
                    return -1
        
                min_difficulties = [[float('inf')] * length for _ in range(days)]
        
                max_diff = 0
                i = 0
                while i <= length - days:
                    max_diff = max(max_diff, jobDifficulty[i])
                    min_difficulties[0][i] = max_diff
                    i += 1
        
                current_day = 1
                while current_day < days:
                    to = current_day
                    while to <= length - days + current_day:
                        current_job_difficulty = jobDifficulty[to]
                        result = float('inf')
                        j = to - 1
                        while j >= current_day - 1:
                            result = min(result, min_difficulties[current_day - 1][j] + current_job_difficulty)
                            current_job_difficulty = max(current_job_difficulty, jobDifficulty[j])
                            j -= 1
                        min_difficulties[current_day][to] = result
                        to += 1
                    current_day += 1
        
                return min_difficulties[days - 1][length - 1]
        

        4.7.907 - 2023-12-28 10:12:36 +0300 MSK

        String Compression II

        Code

        class Solution:
            def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
                n = len(s)
                dp = [[9999] * 110 for _ in range(110)]
                dp[0][0] = 0
        
                for i in range(1, n + 1):
                    for j in range(0, k + 1):
                        cnt, del_ = 0, 0
                        for l in range(i, 0, -1):
                            if s[l - 1] == s[i - 1]:
                                cnt += 1
                            else:
                                del_ += 1
        
                            if j - del_ >= 0:
                                dp[i][j] = min(dp[i][j], dp[l - 1][j - del_] + 1 + (3 if cnt >= 100 else 2 if cnt >= 10 else 1 if cnt >= 2 else 0))
        
                        if j > 0:
                            dp[i][j] = min(dp[i][j], dp[i - 1][j - 1])
        
                return dp[n][k]
        

        4.7.908 - 2023-12-27 11:51:17 +0300 MSK

        Minimum Time to Make Rope Colorful

        Code

        class Solution:
            def minCost(self, colors: str, neededTime: List[int]) -> int:
                totalTime = 0
                i = 0
                j = 0
        
                while i < len(neededTime) and j < len(neededTime):
                    currTotal = 0
                    currMax = 0
        
                    while j < len(neededTime) and colors[i] == colors[j]:
                        currTotal += neededTime[j]
                        currMax = max(currMax, neededTime[j])
                        j += 1
        
                    totalTime += currTotal - currMax
                    i = j
        
                return totalTime
        

        4.7.909 - 2023-12-26 11:08:25 +0300 MSK

        Number of Dice Rolls With Target Sum

        Code

        class Solution:
            mod = 10 ** 9 + 7
        
            def numRollsToTarget(self, n: int, k: int, target: int) -> int:
                dp = [[-1] * (target + 1) for _ in range(n + 1)]
                return self.recursion(dp, n, k, target)
        
            def recursion(self, dp: list, n: int, k: int, target: int) -> int:
                if target == 0 and n == 0:
                    return 1
                if n == 0 or target <= 0:
                    return 0
        
                if dp[n][target] != -1:
                    return dp[n][target] % self.mod
        
                ways = 0
                for i in range(1, k + 1):
                    ways = (ways + self.recursion(dp, n - 1, k, target - i)) % self.mod
        
                dp[n][target] = ways % self.mod
                return dp[n][target]
        

        4.7.910 - 2023-12-25 10:53:55 +0300 MSK

        Decode Ways

        Code

        class Solution:
            def numDecodings(self, s):
                if s == "0":
                    return 0
                
                # dp_0 = dp[i]
                # dp_1 = dp[i + 1]
                # dp_2 = dp[i + 2]
                dp_2 = 1
                dp_1 = int(s[-1] != "0")
        
                i = len(s) - 2
                while i >= 0:
                    if s[i] == "0":
                        dp_0 = 0
                    else:
                        dp_0 = dp_1
                        if (s[i] == "1") or (s[i] == "2" and eval(s[i + 1]) < 7):
                            dp_0 += dp_2
                    i -= 1
                    dp_0, dp_1, dp_2 = 0, dp_0, dp_1
                
                return dp_1
        

        4.7.911 - 2023-12-24 12:54:15 +0300 MSK

        Minimum Changes To Make Alternating Binary String

        Code

        class Solution:
            def minOperations(self, s: str) -> int:
                start0 = 0
                start1 = 0
                
                for i in range(len(s)):
                    if i % 2 == 0:
                        if s[i] == "0":
                            start1 += 1
                        else:
                            start0 += 1
                    else:
                        if s[i] == "1":
                            start1 += 1
                        else:
                            start0 += 1
                
                return min(start0, start1)
        

        4.7.912 - 2023-12-24 00:41:36 +0300 MSK

        Path Crossing

        Code

        class Solution:
            def isPathCrossing(self, path: str) -> bool:
                moves = {
                    "N": (0, 1),
                    "S": (0, -1),
                    "W": (-1, 0),
                    "E": (1, 0)
                }
                
                visited = {(0, 0)}
                x = 0
                y = 0
        
                for c in path:
                    dx, dy = moves[c]
                    x += dx
                    y += dy
                    
                    if (x, y) in visited:
                        return True
        
                    visited.add((x, y))
                
                return False
        

        4.7.913 - 2023-12-22 11:52:14 +0300 MSK

        Maximum Score After Splitting a String

        Code

        class Solution:
            def maxScore(self, s: str) -> int:
                ones = s.count("1")
                zeros = 0
                ans = 0 
        
                for i in range(len(s) - 1):
                    if s[i] == "1":
                        ones -= 1
                    else:
                        zeros += 1
                
                    ans = max(ans, zeros + ones)
                
                return ans
        

        4.7.914 - 2023-12-21 08:42:34 +0300 MSK

        Widest Vertical Area Between Two Points Containing No Points

        Code

        class Solution:
            def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
                points.sort(key=lambda x: x[0])
        
                max_width = 0
        
                for i in range(1, len(points)):
                    width = points[i][0] - points[i-1][0]
                    max_width = max(max_width, width)
        
                return max_width
        

        4.7.915 - 2023-12-20 14:05:16 +0300 MSK

        Buy Two Chocolates

        Code

        class Solution:
            def buyChoco(self, prices: List[int], money: int) -> int:
                # Assume the Minimum Cost to be Infinity
                min_cost = float('inf')
        
                # Number of Chocolates
                n = len(prices)
        
                # Check Every Pair of Chocolates
                for first_choco in range(n):
                    for second_choco in range(first_choco + 1, n):
                        # Sum of Prices of the Two Chocolates
                        cost = prices[first_choco] + prices[second_choco]
        
                        # If the Sum of Prices is Less than the Minimum Cost
                        if cost < min_cost:
                            # Update the Minimum Cost
                            min_cost = cost
                
                # We can buy chocolates only if we have enough money
                if min_cost <= money:
                    # Return the Amount of Money Left
                    return money - min_cost
                else:
                    # We cannot buy chocolates. Return the initial amount of money
                    return money
        

        4.7.916 - 2023-12-19 11:24:47 +0300 MSK

        Image Smoother

        Code

        class Solution:
            def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
                # Save the dimensions of the image.
                m = len(img)
                n = len(img[0])
        
                # Create a new image of the same dimension as the input image.
                smooth_img = [[0] * n for _ in range(m)]
        
                # Iterate over the cells of the image.
                for i in range(m):
                    for j in range(n):
                        # Initialize the sum and count 
                        sum = 0
                        count = 0
        
                        # Iterate over all plausible nine indices.
                        for x in (i - 1, i, i + 1):
                            for y in (j - 1, j, j + 1):
                                # If the indices form valid neighbor
                                if 0 <= x < m and 0 <= y < n:
                                    sum += img[x][y]
                                    count += 1
        
                        # Store the rounded down value in smooth_img[i][j].
                        smooth_img[i][j] = sum // count
                
                # Return the smooth image.
                return smooth_img
        

        4.7.917 - 2023-12-18 13:27:09 +0300 MSK

        Maximum Product Difference Between Two Pairs

        Code

        class Solution:
            def maxProductDifference(self, nums: List[int]) -> int:
                nums.sort()
                return nums[-1] * nums[-2] - nums[0] * nums[1]
        

        4.7.918 - 2023-12-17 12:09:37 +0300 MSK

        Design a Food Rating System

        Code

        class Food:
            def __init__(self, food_rating, food_name):
                # Store the food's rating.
                self.food_rating = food_rating
                # Store the food's name.
                self.food_name = food_name
        
            def __lt__(self, other):
                # Overload the less than operator for comparison.
                # If food ratings are the same, sort based on their name (lexicographically smaller name food will be on top).
                if self.food_rating == other.food_rating:
                    return self.food_name < other.food_name
                # Sort based on food rating (bigger rating food will be on top).
                return self.food_rating > other.food_rating
        
        class FoodRatings:
            def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
                # Map food with its rating.
                self.food_rating_map = {}
                # Map food with the cuisine it belongs to.
                self.food_cuisine_map = {}
                # Store all food of a cuisine in a priority queue (to sort them on ratings/name).
                # Priority queue element -> Food: (food_rating, food_name)
                self.cuisine_food_map = defaultdict(list)
        
                for i in range(len(foods)):
                    # Store 'rating' and 'cuisine' of the current 'food' in 'food_rating_map' and 'food_cuisine_map' maps.
                    self.food_rating_map[foods[i]] = ratings[i]
                    self.food_cuisine_map[foods[i]] = cuisines[i]
                    # Insert the '(rating, name)' element into the current cuisine's priority queue.
                    heapq.heappush(self.cuisine_food_map[cuisines[i]], Food(ratings[i], foods[i]))
        
            def changeRating(self, food: str, newRating: int) -> None:
                # Update food's rating in 'food_rating' map.
                self.food_rating_map[food] = newRating
                # Insert the '(new rating, name)' element in the respective cuisine's priority queue.
                cuisineName = self.food_cuisine_map[food]
                heapq.heappush(self.cuisine_food_map[cuisineName], Food(newRating, food))
        
            def highestRated(self, cuisine: str) -> str:
                # Get the highest rated 'food' of 'cuisine'.
                highest_rated = self.cuisine_food_map[cuisine][0]
        
                # If the latest rating of 'food' doesn't match with the 'rating' on which it was sorted in the priority queue,
                # then we discard this element from the priority queue.
                while self.food_rating_map[highest_rated.food_name] != highest_rated.food_rating:
                    heapq.heappop(self.cuisine_food_map[cuisine])
                    highest_rated = self.cuisine_food_map[cuisine][0]
        
                # Return the name of the highest-rated 'food' of 'cuisine'.
                return highest_rated.food_name
        

        4.7.919 - 2023-12-16 13:01:55 +0300 MSK

        Valid Anagram

        Code

        class Solution:
            def isAnagram(self, s: str, t: str) -> bool:
                if (len(s) != len(t)):
                    return False
                    
                letters = [0] * 26
                for char in s:
                    letters[ord(char) - ord('a')] += 1
                
                for char in t:
                    i = ord(char) - ord('a')
                    letters[i] -= 1
                    if letters[i] < 0:
                        return False
        
                return True
        

        4.7.920 - 2023-12-15 10:56:18 +0300 MSK

        Destination City

        Code

        class Solution:
            def destCity(self, paths: List[List[str]]) -> str:
                paths_from = set()
                for path_from, path_to in paths:
                    paths_from.add(path_from)
                
                ans = ""
                for _, path_to in paths:
                    if path_to not in paths_from:
                        ans = path_to
                        break
                
                return ans
        

        4.7.921 - 2023-12-15 10:54:52 +0300 MSK

        Destination City

        Code

        class Solution:
            def destCity(self, paths: List[List[str]]) -> str:
                paths_from, paths_to = set(), set()
                for path_from, path_to in paths:
                    paths_from.add(path_from)
                    paths_to.add(path_to)
                
                return (paths_to - paths_from).pop()
        

        4.7.922 - 2023-12-14 12:30:55 +0300 MSK

        Difference Between Ones and Zeros in Row and Column

        Code

        class Solution:
            def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]:
                m = len(grid)
                n = len(grid[0])
        
                rows = {}
                for r in range(m):        
                    row_sum = 0
                    for c in range(n):
                        row_sum += grid[r][c]
                    
                    rows[r] = row_sum
        
                cols = {}
                for c in range(n):
                    col_sum = 0
                    for r in range(m):
                        col_sum += grid[r][c]
                    
                    cols[c] = col_sum
        
                res = [[0] * n for _ in range(m)]
        
                for r in range(m):
                    for c in range(n):
                        res[r][c] = rows[r] + cols[c] - (m - rows[r]) - (n - cols[c])
                
                return res
        

        4.7.923 - 2023-12-13 11:11:00 +0300 MSK

        Special Positions in a Binary Matrix

        Code

        class Solution:
            def numSpecial(self, mat: List[List[int]]) -> int:
                def get_column_sum(col_idx):
                    return sum(row[col_idx] for row in mat)
        
                special = 0
                for row in mat:
                    if sum(row) == 1:
                        col_idx = row.index(1)
                        special += get_column_sum(col_idx) == 1
        
                return special
        

        4.7.924 - 2023-12-12 10:39:45 +0300 MSK

        Maximum Product of Two Elements in an Array

        Code

        class Solution:
            def maxProduct(self, nums: List[int]) -> int:
                biggest = 0
                second_biggest = 0
                for num in nums:
                    if num > biggest:
                        second_biggest = biggest
                        biggest = num
                    else:
                        second_biggest = max(second_biggest, num)
                
                return (biggest - 1) * (second_biggest - 1)
        

        4.7.925 - 2023-12-11 15:30:35 +0300 MSK

        Keyboard Row

        Code

        class Solution:
            def findWords(self, words: List[str]) -> List[str]:
                ans = []
                rows = [
                    set("qwertyuiop"),
                    set("asdfghjkl"), 
                    set("zxcvbnm")
                ]
                for word in words:
                    for row in rows:
                        if len(row.union(word.lower())) == len(row):
                            ans.append(word)
                            break
                return ans
        

        4.7.926 - 2023-12-11 10:26:55 +0300 MSK

        Element Appearing More Than 25% In Sorted Array

        Code

        class Solution:
            def findSpecialInteger(self, arr: List[int]) -> int:
                prev, count = arr[0], 1
                quarter = len(arr) / 4
                for num in arr[1:]:
                    if num == prev:
                        count += 1
                    else:
                        prev = num
                        count = 1
                    if count > quarter:
                        break
                return prev
        

        4.7.927 - 2023-12-10 13:46:54 +0300 MSK

        Binary Tree Inorder Traversal

        Code

        /**
         * Definition for a binary tree node.
         * struct TreeNode {
         *     int val;
         *     TreeNode *left;
         *     TreeNode *right;
         *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
         *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
         *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
         * };
         */
        class Solution {
        public:
            vector<int> inorderTraversal(TreeNode* root) {
                vector<int> result;
                helper(root, result);
                return result;
            }
        
            void helper(TreeNode* root, vector<int>& result) {
                if (root != nullptr) {
                    helper(root->left, result);
                    result.push_back(root->val);
                    helper(root->right, result);
                }
            }
        };
        

        4.7.928 - 2023-12-10 13:46:22 +0300 MSK

        Binary Tree Inorder Traversal

        Code

        /**
         * Definition for a binary tree node.
         * struct TreeNode {
         *     int val;
         *     TreeNode *left;
         *     TreeNode *right;
         *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
         *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
         *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
         * };
         */
        class Solution {
        public:
            vector<int> inorderTraversal(TreeNode* root) {
                vector<int> result;
                helper(root, result);
                return result;
            }
        
            void helper(TreeNode* root, vector<int>& result) {
                if (root != nullptr) {
                    helper(root->left, result);
                    result.push_back(root->val);
                    helper(root->right, result);
                }
            }
        };
        

        4.7.929 - 2023-12-10 13:45:46 +0300 MSK

        Transpose Matrix

        Code

        class Solution {
        public:
            vector<vector<int>> transpose(vector<vector<int>>& matrix) {
                int row = matrix.size();
                int col = matrix[0].size();
                vector<vector<int>> result(col, vector<int>(row, 0));
                
                for (int i = 0; i < col; ++i) {
                    for (int j = 0; j < row; ++j) {
                        result[i][j] = matrix[j][i];
                    }
                }
                
                return result;
            }
        };
        

        4.7.930 - 2023-12-08 21:03:57 +0300 MSK

        Construct String from Binary Tree

        Code

        class Solution {
        public:
            string tree2str(TreeNode* root) {
                string str = "";
                 check(root, str);
                 return str;
            }
            void check(TreeNode* root, string &str) {
                if (root == NULL) {
                    return;
                }
                str += to_string(root->val);
                if (root->left || root->right) {
                    str += '(';
                    check(root->left, str);
                    str += ')';
                }
                if (root->right) {
                    str += '(';
                    check(root->right, str);
                    str += ')';
                }
                
            }
            
        };
        

        4.7.931 - 2023-12-07 19:20:48 +0300 MSK

        Largest Odd Number in String

        Code

        class Solution {
        public:
            string largestOddNumber(string num) {
                size_t length {num.size()};
                for (int i = length - 1; i >= 0; --i) {
                    if ((num[i] - '0') % 2 != 0) {
                        return num.substr(0, i + 1);
                    }
                }
                return "";
            }
        };
        

        4.7.932 - 2023-12-06 12:45:40 +0300 MSK

        Palindrome Linked List

        Code

        class Solution {
        public:
            bool isPalindrome(ListNode* head) {
                ListNode* slow {head};
                ListNode* fast {head};
                ListNode* next;
                ListNode* prev {new ListNode()};
        
                while(fast && fast->next) {
                    slow = slow->next;
                    fast = fast->next->next; 
        
                    next = head->next;
                    head->next = prev;
                    prev = head;
                    head = next;
                }
            
                if (fast) {
                    slow = slow->next;
                }
                head = prev;
        
                while (slow) {
                    if (head->val != slow->val) {
                        return false;
                    }
                    head = head->next;
                    slow = slow->next;
                }
                return true;
            }
        };
        

        4.7.933 - 2023-12-06 09:43:04 +0300 MSK

        Calculate Money in Leetcode Bank

        Code

        class Solution {
        public:
            int totalMoney(int n) {
                int ans {0};
                int monday {1};
                
                while (n > 0) {
                    for (int day {0}; day < min(n, 7); ++day) {
                        ans += monday + day;
                    }
                    n -= 7;
                    ++monday;
                }
                
                return ans;
            }
        };
        

        4.7.934 - 2023-12-05 16:12:24 +0300 MSK

        Count of Matches in Tournament

        Code

        class Solution {
        public:
            int numberOfMatches(int n) {
                int ans = 0;
                while (n > 1) {
                    if (n % 2 == 0) {
                        int matches {n / 2};
                        ans += matches;
                        n = matches;
                    } else {
                        int matches {(n - 1) / 2};
                        ans += matches;
                        n = matches + 1;
                    }
                }
                
                return ans;
            }
        };
        

        4.7.935 - 2023-12-04 11:09:00 +0300 MSK

        Largest 3-Same-Digit Number in String

        Code

        class Solution {
        public:
            string largestGoodInteger(string num) {
                int cur {-1};
                int max {-1};
                int count {0};
                for (const char& ch : num) {
                    int i {ch - '0'};
                    if (i == cur) {
                        ++count;
                    } else {
                        cur = i;
                        count = 1; 
                    }
                    if (count == 3) {
                        max = std::max(i, max);
                    }
                }
                if (max == -1) {
                    return "";
                }
                std::string ans {std::to_string(max)};
                return ans + ans + ans;
            }
        };
        

        4.7.936 - 2023-12-03 17:53:13 +0300 MSK

        Minimum Time Visiting All Points

        Code

        class Solution {
        public:
            int minTimeToVisitAllPoints(vector<vector<int>>& points) {
                int ans = 0;
                for (int i = 0; i < points.size() - 1; i++) {
                    int currX = points[i][0];
                    int currY = points[i][1];
                    int targetX = points[i + 1][0];
                    int targetY = points[i + 1][1];
                    ans += max(abs(targetX - currX), abs(targetY - currY));
                }
                
                return ans;
            }
        };
        

        4.7.937 - 2023-12-02 23:40:09 +0300 MSK

        Find Words That Can Be Formed by Characters

        Code

        class Solution {
        public:
            int countCharacters(vector<string>& words, string chars) {
                std::vector<int> count {};
                int ans {};
                count.resize(26);
                for (const char& ch : chars) {
                    ++count[ch - 'a'];
                }
                for (const string& word : words) {
                    std::vector<int> wordCount {};
                    wordCount.resize(26);
                    bool failure {false};
                    for (const char& ch : word) {
                        int i {ch - 'a'};
                        int cur {++wordCount[i]};
                        if (cur > count[i]) {
                            failure = true;
                            break;
                        }
                    }
                    if (!failure) {
                        ans += word.length();
                    }
                }
                return ans;
            }
        };
        

        4.7.938 - 2023-12-01 11:21:29 +0300 MSK

        Check If Two String Arrays are Equivalent

        Code

        class Solution {
        public:
            bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
                string s1 = "";
                string s2 = "";
        
                for(const string& s : word1) {
                    s1 += s;
                }
                for(const string& s : word2) {
                    s2 += s;
                }
                return s1==s2;
            }
        };
        

        4.7.939 - 2023-11-30 10:50:12 +0300 MSK

        Minimum One Bit Operations to Make Integers Zero

        Code

        class Solution {
        public:
            int minimumOneBitOperations(int n) {
                if (n == 0) {
                    return 0;
                }
                
                int k = 0;
                int curr = 1;
                while (curr * 2 <= n) {
                    curr *= 2;
                    k++;
                }
                
                return (1 << (k + 1)) - 1 - minimumOneBitOperations(n ^ curr);
            }
        };
        

        4.7.940 - 2023-11-29 12:01:45 +0300 MSK

        Number of 1 Bits

        Code

        class Solution {
        public:
            int hammingWeight(uint32_t n) {
                int ans {};
                while (n) {
                    if (n & 1) {
                        ++ans;
                    }
                    n >>= 1;
                }
                return ans;
            }
        };
        

        4.7.941 - 2023-11-28 13:04:41 +0300 MSK

        Number of Ways to Divide a Long Corridor

        Code

        class Solution {
        public:
            // Store 1000000007 in a variable for convenience
            const int MOD = 1e9 + 7;
            
            // Count the number of ways to divide from "index" to the last index
            // with "seats" number of "S" in the current section
            int count(int index, int seats, string& corridor, int cache[][3]) {
                // If we have reached the end of the corridor, then
                // the current section is valid only if "seats" is 2
                if (index == corridor.length()) {
                    return seats == 2 ? 1 : 0;
                }
        
                // If we have already computed the result of this sub-problem,
                // then return the cached result
                if (cache[index][seats] != -1) {
                    return cache[index][seats];
                }
        
                // Result of the sub-problem
                int result = 0;
        
                // If the current section has exactly 2 "S"
                if (seats == 2) {
                    // If the current element is "S", then we have to close the
                    // section and start a new section from this index. Next index
                    // will have one "S" in the current section
                    if (corridor[index] == 'S') {
                        result = count(index + 1, 1, corridor, cache);
                    } else {
                        // If the current element is "P", then we have two options
                        // 1. Close the section and start a new section from this index
                        // 2. Keep growing the section
                        result = (count(index + 1, 0, corridor, cache) + count(index + 1, 2, corridor, cache)) % MOD;  
                    }
                } else {
                    // Keep growing the section. Increment "seats" if present
                    // element is "S"
                    if (corridor[index] == 'S') {
                        result = count(index + 1, seats + 1, corridor, cache);
                    } else {
                        result = count(index + 1, seats, corridor, cache);
                    }
                }
        
                // Memoize the result, and return it
                cache[index][seats] = result;
                return cache[index][seats];
            }
        
            int numberOfWays(string corridor) {
                // Cache the result of each sub-problem
                int cache[corridor.length()][3];
                memset(cache, -1, sizeof(cache));
        
                // Call the count function
                return count(0, 0, corridor, cache);
            }
        };
        

        4.7.942 - 2023-11-27 10:32:44 +0300 MSK

        Largest Submatrix With Rearrangements

        Code

        class Solution {
        public:
            int largestSubmatrix(vector<vector<int>>& matrix) {
                int m = matrix.size();
                int n = matrix[0].size();
                int ans = 0;
                
                for (int row = 0; row < m; row++) {
                    for (int col = 0; col < n; col++) {
                        if (matrix[row][col] != 0 && row > 0) {
                            matrix[row][col] += matrix[row - 1][col];
                        }
                    }
                    
                    vector<int> currRow = matrix[row];
                    sort(currRow.begin(), currRow.end(), greater());
                    for (int i = 0; i < n; i++) {
                        ans = max(ans, currRow[i] * (i + 1));
                    }
                }
                
                return ans;
            }
        };
        

        4.7.943 - 2023-11-27 10:32:13 +0300 MSK

        Knight Dialer

        Code

        class Solution {
        public:
            vector<vector<int>> memo;
            int n;
            int MOD = 1e9 + 7;
            vector<vector<int>> jumps = {
                {4, 6},
                {6, 8},
                {7, 9},
                {4, 8},
                {3, 9, 0},
                {},
                {1, 7, 0},
                {2, 6},
                {1, 3},
                {2, 4}
            };
            
            int dp(int remain, int square) {
                if (remain == 0) {
                    return 1;
                }
                
                if (memo[remain][square] != 0) {
                    return memo[remain][square];
                }
                
                int ans = 0;
                for (int nextSquare : jumps[square]) {
                    ans = (ans + dp(remain - 1, nextSquare)) % MOD;
                }
                
                memo[remain][square] = ans;
                return ans;
            }
            
            int knightDialer(int n) {
                this->n = n;
                memo = vector(n + 1, vector(10, 0));
                int ans = 0;
                for (int square = 0; square < 10; square++) {
                    ans = (ans + dp(n - 1, square)) % MOD;
                }
                
                return ans;
            }
        };
        

        4.7.944 - 2023-11-25 22:00:45 +0300 MSK

        Sum of Absolute Differences in a Sorted Array

        Code

        class Solution {
        public:
            vector<int> getSumAbsoluteDifferences(vector<int>& nums) {
                int n = nums.size();
                int totalSum = accumulate(nums.begin(), nums.end(), 0);
                
                int leftSum = 0;
                vector<int> ans;
                for (int i = 0; i < n; i++) {
                    int rightSum = totalSum - leftSum - nums[i];
                    
                    int leftCount = i;
                    int rightCount = n - 1 - i;
                    
                    int leftTotal = leftCount * nums[i] - leftSum;
                    int rightTotal = rightSum - rightCount * nums[i];
                    
                    ans.push_back(leftTotal + rightTotal);
                    leftSum += nums[i];
                }
                
                return ans;
            }
        };
        

        4.7.945 - 2023-11-25 22:00:22 +0300 MSK

        Sum of Absolute Differences in a Sorted Array

        Code

        class Solution {
        public:
            vector<int> getSumAbsoluteDifferences(vector<int>& nums) {
                int n = nums.size();
                vector<int> prefix = {nums[0]};
                for (int i = 1; i < n; i++) {
                    prefix.push_back(prefix[i - 1] + nums[i]);
                }
                vector<int> ans;
                for (int i = 0; i < n; i++) {
                    int leftSum = prefix[i] - nums[i];
                    int rightSum = prefix[n - 1] - prefix[i];
                    
                    int leftCount = i;
                    int rightCount = n - 1 - i;
                    
                    int leftTotal = leftCount * nums[i] - leftSum;
                    int rightTotal = rightSum - rightCount * nums[i];
                    
                    ans.push_back(leftTotal + rightTotal);
                }
                return ans;
            }
        };
        

        4.7.946 - 2023-11-24 16:49:32 +0300 MSK

        Kids With the Greatest Number of Candies

        Code

        class Solution {
        public:
            std::vector<bool> kidsWithCandies(std::vector<int>& candies, int extraCandies) {
                size_t length {candies.size()};        
                std::vector<bool> ans {};
                ans.resize(length);
                const int maxCandy {*std::max_element(candies.begin(), candies.end())};
                for (size_t i = 0; i < length; ++i) {
                    ans[i] = (candies[i] + extraCandies) >= maxCandy;
                }
                return ans;
            }
        };
        

        4.7.947 - 2023-11-24 16:37:41 +0300 MSK

        Greatest Common Divisor of Strings

        Code

        class Solution {
        public:
            string gcdOfStrings(string str1, string str2) {
                if (str1 + str2 == str2 + str1) {
                    return str1.substr(0, std::gcd(str1.size(), str2.size()));
                }
                return "";
            }
        };
        

        4.7.948 - 2023-11-24 16:36:38 +0300 MSK

        Greatest Common Divisor of Strings

        Code

        class Solution {
        public:
            string gcdOfStrings(string str1, string str2) {
                if (str1 + str2 != str2 + str1) {
                    return "";
                }
                unsigned long gcdLength {std::gcd(str1.size(), str2.size())};
                return str1.substr(0, gcdLength);
            }
        };
        

        4.7.949 - 2023-11-24 16:32:52 +0300 MSK

        Greatest Common Divisor of Strings

        Code

        class Solution {
        public:
            bool valid(string str1, string str2, size_t k) {
                size_t len1 {str1.size()}, len2 {str2.size()};
                if (len1 % k != 0 || len2 % k != 0) {
                    return false;
                }
                string base = str1.substr(0, k);
                size_t n1 {len1 / k}, n2 {len2 / k};
                if (n1 == n2) {
                    return str1 == str2 && joinWords(base, n1) == str1;
                }
                return str1 == joinWords(base, n1) && str2 == joinWords(base, n2);
            }
        
            string joinWords(string str, size_t k) {
                string ans = "";
                for (size_t i = 0; i < k; ++i) {
                    ans += str;
                }
                return ans;
            }
            
            
            string gcdOfStrings(string str1, string str2) {
                for (size_t i = min(str1.size(), str2.size()); i > 0; --i) {
                    if (valid(str1, str2, i)) {
                        return str1.substr(0, i);
                    }
                }
                return "";
            }
        };
        

        4.7.950 - 2023-11-24 11:07:37 +0300 MSK

        Maximum Number of Coins You Can Get

        Code

        class Solution {
        public:
            int maxCoins(vector<int>& piles) {
                std::sort(piles.begin(), piles.end());
                size_t length {piles.size()};
                size_t picks {length / 3};
                int count {};
                for (size_t i {length - 2}; picks > 0; i -= 2, --picks) {
                    count += piles[i];
                }
                return count;
            }
        };
        

        4.7.951 - 2023-11-23 13:41:25 +0300 MSK

        Arithmetic Subarrays

        Code

        class Solution {
        public:
            bool check(vector<int>& arr) {
                sort(arr.begin(), arr.end());
                int diff = arr[1] - arr[0];
                
                for (int i = 2; i < arr.size(); i++) {
                    if (arr[i] - arr[i - 1] != diff) {
                        return false;
                    }
                }
                
                return true;
            }
            
            vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) {
                vector<bool> ans;
                for (int i = 0; i < l.size(); i++) {
                    vector<int> arr(begin(nums) + l[i], begin(nums) + r[i] + 1);
                    ans.push_back(check(arr));
                }
                
                return ans;
            }
        };
        

        4.7.952 - 2023-11-22 18:49:02 +0300 MSK

        Diagonal Traverse II

        Code

        class Solution {
        public:
            vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
                unordered_map<int, vector<int>> groups;
                for (int row = nums.size() - 1; row >= 0; row--) {
                    for (int col = 0; col < nums[row].size(); col++) {
                        int diagonal = row + col;
                        groups[diagonal].push_back(nums[row][col]);
                    }
                }
                
                vector<int> ans;
                int curr = 0;
                
                while (groups.find(curr) != groups.end()) {
                    for (int num : groups[curr]) {
                        ans.push_back(num);
                    }
                    
                    curr++;
                }
                
                return ans;
            }
        };
        

        4.7.953 - 2023-11-21 12:51:21 +0300 MSK

        Binary Tree Paths

        Code

        /**
         * Definition for a binary tree node.
         * struct TreeNode {
         *     int val;
         *     TreeNode *left;
         *     TreeNode *right;
         *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
         *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
         *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
         * };
         */
        class Solution {
        public:
            vector<string> binaryTreePaths(TreeNode* root) {
                vector<string> ans;
                dfs(*root, ans, "");
                return ans;
            }
        
            void dfs(TreeNode& root, vector<string> &ans, string path){
                path += (path.size() ? "->" : "") + std::to_string(root.val);
                if(!root.left && !root.right) {
                    ans.push_back(path);
                    return;
                }
                if(root.left) {
                    dfs(*root.left, ans, path);
                }
                if(root.right) {
                    dfs(*root.right, ans, path);
                }
            }
        };
        

        4.7.954 - 2023-11-21 12:44:04 +0300 MSK

        Count Nice Pairs in an Array

        Code

        class Solution {
        public:
            int countNicePairs(vector<int>& nums) {
                std::unordered_map<int, int> diffs{};
                int ans{};
                double mod{1e9 + 7};
                for (const int& num : nums) {
                    int revNum{};
                    int tempNum{num};
                    while(tempNum) {
                        revNum = (revNum * 10) + (tempNum % 10);
                        tempNum /= 10;
                    }
                    int diff{num-revNum};
                    if (diffs.contains(diff)) {
                        ans = std::fmod(ans + diffs[diff], mod);
                    }
                    ++diffs[diff];
                }
                return ans;
            }
        
        };
        

        4.7.955 - 2023-11-21 12:33:13 +0300 MSK

        Count Nice Pairs in an Array

        Code

        class Solution {
        public:
            int countNicePairs(vector<int>& nums) {
                std::unordered_map<int, int> diffs{};
                for (const int& num : nums) {
                    int revNum{};
                    int tempNum{num};
                    while(tempNum) {
                        revNum = (revNum * 10) + (tempNum % 10);
                        tempNum /= 10;
                    }
                    ++diffs[num - revNum];
                }
                int ans{};
                double mod{std::pow(10, 9) + 7};
                for (const auto& [num, count] : diffs) {
                    long pairs{(1L * count * count - count) / 2};
                    ans = std::fmod(ans + pairs, mod);
                }
                return ans;
            }
        
        };
        

        4.7.956 - 2023-11-20 18:30:57 +0300 MSK

        Excel Sheet Column Number

        Code

        class Solution {
        public:
            int titleToNumber(string columnTitle) {
                int ans{0};
                for (const char& ch : columnTitle) {
                    ans = (ans * 26) + (ch - 'A') + 1;
                }
                return ans;
            }
        };
        

        4.7.957 - 2023-11-20 14:40:36 +0300 MSK

        Binary Tree Postorder Traversal

        Code

        /**
         * Definition for a binary tree node.
         * struct TreeNode {
         *     int val;
         *     TreeNode *left;
         *     TreeNode *right;
         *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
         *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
         *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
         * };
         */
        class Solution {
        public:
            vector<int> postorderTraversal(TreeNode* root) {
                if (root == nullptr) {
                    return {};
                }
                std::vector<int> ans{};
                addNodes(*root, ans);
                return ans;
            }
        
            void addNodes(TreeNode& node, std::vector<int>& ans) {
                if (node.left != nullptr) {
                    addNodes(*node.left, ans);
                }
                if (node.right != nullptr) {
                    addNodes(*node.right, ans);
                }
                ans.push_back(node.val);
            }
        };
        

        4.7.958 - 2023-11-20 14:38:40 +0300 MSK

        Binary Tree Postorder Traversal

        Code

        /**
         * Definition for a binary tree node.
         * struct TreeNode {
         *     int val;
         *     TreeNode *left;
         *     TreeNode *right;
         *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
         *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
         *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
         * };
         */
        class Solution {
        public:
            vector<int> postorderTraversal(TreeNode* root) {
                if (root == nullptr) {
                    return {};
                }
                std::vector<int> ans{};
                addNodes(root, ans);
                return ans;
            }
        
            void addNodes(TreeNode* node, std::vector<int>& ans) {
                auto left{node->left}, right{node->right};
                if (left != nullptr) {
                    addNodes(left, ans);
                }
                if (right != nullptr) {
                    addNodes(right, ans);
                }
                ans.push_back(node->val);
            }
        };
        

        4.7.959 - 2023-11-20 14:31:25 +0300 MSK

        Binary Tree Preorder Traversal

        Code

        /**
         * Definition for a binary tree node.
         * struct TreeNode {
         *     int val;
         *     TreeNode *left;
         *     TreeNode *right;
         *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
         *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
         *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
         * };
         */
        class Solution {
        public:
            vector<int> preorderTraversal(TreeNode* root) {
                if (root == nullptr) {
                    return {};
                }
                std::vector<int> ans{};
                std::vector<TreeNode*> q{root};
                while (q.size() != 0) {
                    auto node = q.back();
                    auto left{node->left}, right{node->right};
                    q.pop_back();
                    ans.push_back(node->val);
                    if (right != nullptr) {
                        q.push_back(right);
                    }
                    if (left != nullptr) {
                        q.push_back(left);
                    }
                }
                return ans;
            }
        };
        

        4.7.960 - 2023-11-20 14:29:40 +0300 MSK

        Binary Tree Preorder Traversal

        Code

        /**
         * Definition for a binary tree node.
         * struct TreeNode {
         *     int val;
         *     TreeNode *left;
         *     TreeNode *right;
         *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
         *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
         *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
         * };
         */
        class Solution {
        public:
            vector<int> preorderTraversal(TreeNode* root) {
                if (root == nullptr) {
                    return {};
                }
                std::vector<int> ans{};
                std::deque<TreeNode*> q{root};
                while (q.size() != 0) {
                    auto node = q.front();
                    auto left{node->left}, right{node->right};
                    q.pop_front();
                    ans.push_back(node->val);
                    if (right != nullptr) {
                        q.push_front(right);
                    }
                    if (left != nullptr) {
                        q.push_front(left);
                    }
                }
                return ans;
            }
        };
        

        4.7.961 - 2023-11-20 14:27:13 +0300 MSK

        Binary Tree Preorder Traversal

        Code

        /**
         * Definition for a binary tree node.
         * struct TreeNode {
         *     int val;
         *     TreeNode *left;
         *     TreeNode *right;
         *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
         *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
         *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
         * };
         */
        class Solution {
        public:
            vector<int> preorderTraversal(TreeNode* root) {
                std::vector<int> ans{};
                std::deque<TreeNode*> q{root};
                while (q.size() != 0) {
                    auto node = q.front();
                    q.pop_front();
                    if (node == nullptr) {
                        continue;
                    }
                    ans.push_back(node->val);
                    q.push_front(node->right);
                    q.push_front(node->left);
                }
                return ans;
            }
        };
        

        4.7.962 - 2023-11-20 14:11:47 +0300 MSK

        Minimum Amount of Time to Collect Garbage

        Code

        class Solution {
        public:
            int garbageCollection(vector<string>& garbage, vector<int>& travel) {
                vector<int> prefixSum(travel.size() + 1, 0);
                prefixSum[1] = travel[0];
                for (int i = 1; i < travel.size(); i++) {
                    prefixSum[i + 1] = prefixSum[i] + travel[i];
                }
                unordered_map<char, int> garbageLastPos;
                unordered_map<char, int> garbageCount;
                for (int i = 0; i < garbage.size(); i++) {
                    for (char c : garbage[i]) {
                        garbageLastPos[c] = i;
                        garbageCount[c]++;
                    }
                }
                char garbageTypes[3] = {'M', 'P', 'G'};
                int ans = 0;
                for (char c : garbageTypes) {
                    if (garbageCount[c]) {
                        ans += prefixSum[garbageLastPos[c]] + garbageCount[c];
                    }
                }
                return ans;
            }
        };
        

        4.7.963 - 2023-11-19 11:31:05 +0300 MSK

        Reduction Operations to Make the Array Elements Equal

        Code

        class Solution {
        public:
            int reductionOperations(vector<int>& nums) {
                sort(nums.begin(), nums.end());
                int ans = 0;
                int up = 0;
                auto length {nums.size()};
                for (int i = 1; i < length; ++i) {
                    if (nums[i] != nums[i - 1]) {
                        ++up;
                    }
                    ans += up;
                }
                return ans;
            }
        };
        

        4.7.964 - 2023-11-18 19:23:48 +0300 MSK

        Frequency of the Most Frequent Element

        Code

        class Solution {
        public:
            int maxFrequency(vector<int>& nums, int k) {
                sort(nums.begin(), nums.end());
                int left = 0;
                int ans = 0;
                long curr = 0;
                
                for (int right = 0; right < nums.size(); right++) {
                    long target = nums[right];
                    curr += target;
                    
                    while ((right - left + 1) * target - curr > k) {
                        curr -= nums[left];
                        left++;
                    }
                    
                    ans = max(ans, right - left + 1);
                }
                
                return ans;
            }
        };
        

        4.7.965 - 2023-11-17 17:25:22 +0300 MSK

        Odd Even Linked List

        Code

        /**
         * Definition for singly-linked list.
         * struct ListNode {
         *     int val;
         *     ListNode *next;
         *     ListNode() : val(0), next(nullptr) {}
         *     ListNode(int x) : val(x), next(nullptr) {}
         *     ListNode(int x, ListNode *next) : val(x), next(next) {}
         * };
         */
        class Solution {
        public:
            ListNode* oddEvenList(ListNode* head) {
                if(!head || !head->next || !head->next->next) {
                    return head;
                } 
                
                ListNode* odd {head};
                ListNode* even {head->next};
                ListNode* even_start {head->next};
                
                while(odd->next && even->next) {
                    ListNode* next {even->next}; 
                    odd->next = next;
                    even->next = next->next;
                    odd = odd->next;
                    even = even->next;
                }
                odd->next = even_start;
                return head; 
            }
        };
        

        4.7.966 - 2023-11-17 16:41:37 +0300 MSK

        Dota2 Senate

        Code

        class Solution {
        public:
            string predictPartyVictory(string senate) {
                std::queue<int> rad, dir;
                unsigned long length {senate.size()};
                for (int i = 0; i < length; ++i){
                    if (senate[i] == 'R'){
                        rad.push(i);
                    } else {
                        dir.push(i);
                    }
                }
                while (!rad.empty() && !dir.empty()) {
                    if (rad.front() < dir.front()) {
                        rad.push(length);
                    } else {
                        dir.push(length);
                    }
                    ++length;
                    rad.pop();
                    dir.pop();
                }
                return rad.empty() ? "Dire" : "Radiant";
            }
        };
        

        4.7.967 - 2023-11-17 14:05:35 +0300 MSK

        Decode String

        Code

        class Solution {
        public:
            string decodeString(string s) {
                return std::get<1>(decode(0, s));
            }
            
            std::tuple<int, string> decode(int pos, string s) {
                int num {0};
                string word {""};
                unsigned long length {s.size()};
                for(; pos < length; ++pos) {
                    char c = s[pos];
                    if(c == '[') {
                        auto [newPos, repeat] {decode(++pos, s)};
                        for(; num > 0; --num) {
                            word += repeat;
                        }
                        pos = newPos;
                    } else if (c >= '0' && c <='9') {
                        num = num * 10 + (c - '0');
                    } else if (c == ']') {
                        return {pos, word};
                    } else {
                        word += c;
                    }
                }
                return {pos, word};
            }
        };
        

        4.7.968 - 2023-11-17 14:02:06 +0300 MSK

        Decode String

        Code

        class Solution {
        public:
            string decodeString(string s) {
                int pos = 0;
                return decode(pos, s);
            }
            
            string decode(int& pos, string s) {
                int num {0};
                string word {""};
                unsigned long length {s.size()};
                for(; pos < length; ++pos) {
                    char c = s[pos];
                    if(c == '[') {
                        string repeat {decode(++pos, s)};
                        for(; num > 0; --num) {
                            word += repeat;
                        }
                    } else if (c >= '0' && c <='9') {
                        num = num * 10 + (c - '0');
                    } else if (c == ']') {
                        return word;
                    } else {
                        word += c;
                    }
                }
                return word;
            }
        };
        

        4.7.969 - 2023-11-17 13:13:32 +0300 MSK

        Removing Stars From a String

        Code

        class Solution {
        public:
            string removeStars(string s) {
                std::string ans;
                int remove {0};
                for (int i = s.size() - 1; i >= 0; --i) {
                    char c = s[i];
                    if (c == '*') {
                        ++remove;
                    } else if (remove == 0) {
                        ans += c;
                    } else {
                        --remove;
                    }
                }
                std::reverse(ans.begin(), ans.end());
                return ans;
            }
        };
        

        4.7.970 - 2023-11-17 13:12:34 +0300 MSK

        Removing Stars From a String

        Code

        class Solution {
        public:
            string removeStars(string s) {
                std::string ans;
                unsigned long length {s.size()};
                int remove {0};
                for (int i = length - 1; i >= 0; --i) {
                    char c = s[i];
                    if (c == '*') {
                        ++remove;
                        continue;
                    }
                    if (remove == 0) {
                        ans += c;
                    } else {
                        --remove;
                    }
                }
                std::reverse(ans.begin(), ans.end());
                return ans;
            }
        };
        

        4.7.971 - 2023-11-17 13:02:26 +0300 MSK

        Minimize Maximum Pair Sum in Array

        Code

        class Solution {
        public:
            int minPairSum(vector<int>& nums) {
                std::sort(nums.begin(), nums.end());
                unsigned long length {nums.size()};
                int maxSum {0};
                for (int i = 0; i < length / 2; ++i) {
                    maxSum = max(maxSum, nums[i] + nums[length - i - 1]);
                }
                return maxSum;
            }
        };
        

        4.7.972 - 2023-11-16 16:43:00 +0300 MSK

        Unique Number of Occurrences

        Code

        class Solution {
        public:
            bool uniqueOccurrences(vector<int>& arr) {
                std::unordered_map<int, int> counts;
                std::unordered_set<int> encountered;
                for (int num : arr) {
                    counts[num] += 1;
                }
                for (const auto [num, count] : counts) {
                    if (encountered.find(count) == encountered.end()) {
                        encountered.insert(count);
                    } else {
                        return false;
                    }
                }
                return true;
            }
        };
        

        4.7.973 - 2023-11-16 16:22:50 +0300 MSK

        N-th Tribonacci Number

        Code

        class Solution {
        public:
            int tribonacci(int n) {
                if (n == 0) {
                    return 0;
                }
                if (n == 1 || n == 2) {
                    return 1;
                }
                int num1 {0}, num2 {1}, num3 {1};
                for (int i = 3; i <= n; ++i) {
                    int newNum3 = num1 + num2 + num3; 
                    num1 = num2;
                    num2 = num3;
                    num3 = newNum3;
                }
                return num3;
            }
        };
        

        4.7.974 - 2023-11-16 14:30:47 +0300 MSK

        Kth Largest Element in an Array

        Code

        class Solution {
        public:
            int findKthLargest(vector<int>& nums, int k) {
                std::sort(nums.begin(), nums.end(), std::greater<int>());
                return nums[k-1];
            }
        };
        

        4.7.975 - 2023-11-16 14:18:16 +0300 MSK

        Search in a Binary Search Tree

        Code

        /**
         * Definition for a binary tree node.
         * struct TreeNode {
         *     int val;
         *     TreeNode *left;
         *     TreeNode *right;
         *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
         *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
         *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
         * };
         */
        class Solution {
        public:
            TreeNode* searchBST(TreeNode* root, int val) {
                while (root != nullptr) {
                    if (root->val == val) {
                        return root;
                    }
                    if (root->val > val) {
                        root = root->left;
                    } else {
                        root = root->right;
                    }
                }
                return root;
            }
        };
        

        4.7.976 - 2023-11-16 14:15:58 +0300 MSK

        Search in a Binary Search Tree

        Code

        /**
         * Definition for a binary tree node.
         * struct TreeNode {
         *     int val;
         *     TreeNode *left;
         *     TreeNode *right;
         *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
         *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
         *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
         * };
         */
        class Solution {
        public:
            TreeNode* searchBST(TreeNode* root, int val) {
                if (root == nullptr || root->val == val) {
                    return root;
                }
                if (val > root->val) {
                    return searchBST(root->right, val);
                }
                return searchBST(root->left, val);
            }
        };
        

        4.7.977 - 2023-11-16 14:13:23 +0300 MSK

        Find Pivot Index

        Code

        class Solution {
        public:
            int pivotIndex(vector<int>& nums) {
                int left {0}, right {std::accumulate(nums.begin() + 1, nums.end(), 0)};
                unsigned long length {nums.size()};
                if (right == 0) {
                    return 0;
                }
                for (int i = 1; i < length; ++i) {
                    left += nums[i-1];
                    right -= nums[i];
                    if (left == right) {
                        return i;
                    }
                }
                return -1;
            }
        };
        

        4.7.978 - 2023-11-16 14:06:30 +0300 MSK

        Find the Highest Altitude

        Code

        class Solution {
        public:
            int largestAltitude(vector<int>& gain) {
                int att {0}, maxAtt {0};
                for (int num : gain) {
                    att += num;
                    maxAtt = max(maxAtt, att);
                }
                return maxAtt;
            }
        };
        

        4.7.979 - 2023-11-16 11:22:37 +0300 MSK

        Find Unique Binary String

        Code

        class Solution {
        public:
            string findDifferentBinaryString(vector<string>& nums) {
                unordered_set<int> integers;
                for (string num : nums) {
                    integers.insert(stoi(num, 0, 2));
                }
        
                int n = nums.size();
                string ans;
                for (int num = 0; num <= n; num++) {
                    if (integers.find(num) == integers.end()) {
                        ans = bitset<16>(num).to_string();
                        break;
                    }
                }
                return ans.substr(16 - n);
            }
        };
        

        4.7.980 - 2023-11-15 16:53:47 +0300 MSK

        Find the Difference of Two Arrays

        Code

        class Solution {
        public:
            vector<int> getElementsOnlyInFirstList(vector<int>& nums1, vector<int>& nums2) {
                unordered_set<int> onlyInNums1;
                for (int num : nums1) {
                    bool existInNums2 = false;
                    for (int x : nums2) {
                        if (x == num) {
                            existInNums2 = true;
                            break;
                        }
                    }
                    if (!existInNums2) {
                        onlyInNums1.insert(num);
                    }
                }
                return vector<int> (onlyInNums1.begin(), onlyInNums1.end());
            }
            
            vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {
                return {getElementsOnlyInFirstList(nums1, nums2), getElementsOnlyInFirstList(nums2, nums1)};
            }
        };
        

        4.7.981 - 2023-11-15 16:12:27 +0300 MSK

        Increasing Triplet Subsequence

        Code

        class Solution {
        public:
            bool increasingTriplet(vector<int>& nums) {
                auto length{nums.size()};
                int num1{INT_MAX}, num2{INT_MAX}; 
                for (int num : nums) {
                    if (num <= num1) {
                        num1 = num;
                    } else if (num <= num2) {
                        num2 = num;
                    } else {
                        return true;
                    }
                }
                return false;
            }
        };
        

        4.7.982 - 2023-11-15 15:18:40 +0300 MSK

        Maximum Element After Decreasing and Rearranging

        Code

        class Solution {
        public:
            int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {
                std::sort(arr.begin(), arr.end());
                auto length{arr.size()};
                int prev{1};
                for (int i = 1; i < length; ++i) {
                    if (arr[i] != prev) {
                        ++prev;
                    }
                }
                return prev;
            }
        };
        

        4.7.983 - 2023-11-15 15:17:30 +0300 MSK

        Maximum Element After Decreasing and Rearranging

        Code

        class Solution {
        public:
            int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {
                std::sort(arr.begin(), arr.end());
                auto length{arr.size()};
                int prev{1};
                for (int i = 1; i < length; ++i) {
                    if (arr[i] == prev) {
                        continue;
                    }
                    ++prev;
                }
                return prev;
            }
        };
        

        4.7.984 - 2023-11-14 15:39:29 +0300 MSK

        Unique Length-3 Palindromic Subsequences

        Code

        class Solution {
        public:
            int countPalindromicSubsequence(string s) {
                unordered_set<char> letters;
                for (char c : s) {
                    letters.insert(c);
                }
                int ans = 0;
                for (char letter : letters) {
                    int i = -1;
                    int j = 0;
                    for (int k = 0; k < s.size(); k++) {
                        if (s[k] == letter) {
                            if (i == -1) {
                                i = k;
                            }
                            
                            j = k;
                        }
                    }
                    unordered_set<char> between;
                    for (int k = i + 1; k < j; k++) {
                        between.insert(s[k]);
                    }
                    
                    ans += between.size();
                }
                return ans;
            }
        };
        

        4.7.985 - 2023-11-13 20:24:55 +0300 MSK

        Reverse Vowels of a String

        Code

        class Solution {
        public:
            bool isVowel(char ch) {
                return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
                       ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
            }
        
            string reverseVowels(string s) {
                unsigned long length{s.size()};
                unsigned long left{0}, right{length-1};
                while (left < right) {
                    char chLeft{s[left]};
                    char chRight{s[right]};
                    if (!isVowel(chLeft)) {
                        ++left;
                    } else if (!isVowel(chRight)) {
                        --right;
                    } else {
                        s[left] = chRight;
                        s[right] = chLeft;
                        ++left;
                        --right;
                    }
                }
                return s;
            }
        };
        

        4.7.986 - 2023-11-13 10:42:13 +0300 MSK

        Sort Vowels in a String

        Code

        class Solution {
        public:
            // Returns true if the character is a vowel.
            bool isVowel(char c) {
                return c == 'a' || c == 'e' || c == 'o'|| c == 'u'|| c == 'i' 
                    || c == 'A' || c == 'E' || c == 'O'|| c == 'U'|| c == 'I';
            }
            
            string sortVowels(string s) {
                unordered_map<char, int> count;
        
                // Store the frequencies for each character.
                for (char c : s) {
                    if (isVowel(c)) {
                        count[c]++;
                    }
                }
        
                // Sorted string having all the vowels.
                string sortedVowel = "AEIOUaeiou";
                string ans;
                int j = 0;
                for (int i = 0; i < s.size(); i++) {
                    if (!isVowel(s[i])) {
                        ans += s[i];
                    } else {
                        // Skip to the character which is having remaining count.
                        while (count[sortedVowel[j]] == 0) {
                            j++;
                        }
        
                        ans += sortedVowel[j];
                        count[sortedVowel[j]]--;
                    }
                }
                return ans;
            }
        };
        

        4.7.987 - 2023-11-13 10:40:23 +0300 MSK

        Sort Vowels in a String

        Code

        class Solution {
        public:
            string sortVowels(string s) {
                std::map<char, int> vowels{
                    {'A', 0}, {'E', 0}, {'I', 0}, {'O', 0}, {'U', 0},
                    {'a', 0}, {'e', 0}, {'i', 0}, {'o', 0}, {'u', 0}
                };
                unsigned long length{ s.size() };
                for (char ch : s) {
                    if (vowels.contains(ch)) {
                        ++vowels[ch];
                    }
                }
                for (int i = 0; i < length; ++i) {
                    const char ch = s[i];
                    if (!vowels.contains(ch)) {
                        continue;
                    }
                    for (const auto& [orderChar, count] : vowels) {
                        if (count > 0) {
                            s[i] = orderChar;
                            --vowels[orderChar];
                            break;
                        }
                    }
                }
                return s;
            }
        };
        

        4.7.988 - 2023-11-13 10:38:46 +0300 MSK

        Sort Vowels in a String

        Code

        class Solution {
        public:
            string sortVowels(string s) {
                std::map<char, int> vowels{
                    {'A', 0}, {'E', 0}, {'I', 0}, {'O', 0}, {'U', 0},
                    {'a', 0}, {'e', 0}, {'i', 0}, {'o', 0}, {'u', 0}
                };
                const char order[10]{ 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u' };
                unsigned long length{ s.size() };
                for (char ch : s) {
                    if (vowels.contains(ch)) {
                        ++vowels[ch];
                    }
                }
                for (int i = 0; i < length; ++i) {
                    const char ch = s[i];
                    if (!vowels.contains(ch)) {
                        continue;
                    }
                    for (char orderChar : order) {
                        if (vowels[orderChar] > 0) {
                            s[i] = orderChar;
                            --vowels[orderChar];
                            break;
                        }
                    }
                }
                return s;
            }
        };
        

        4.7.989 - 2023-11-12 17:00:22 +0300 MSK

        Maximum Average Subarray I

        Code

        class Solution {
        public:
            double findMaxAverage(vector<int>& nums, int k) {
                int length = nums.size();
                double sum = std::accumulate(nums.begin(), nums.begin() + k , 0);
                double maxSum = sum;
                for (int i = k; i < length; ++i) {
                    sum += nums[i] - nums[i-k];
                    maxSum = max(sum, maxSum);
                }
                return maxSum / k;
            }
        };
        

        4.7.990 - 2023-11-12 16:08:04 +0300 MSK

        String Compression

        Code

        class Solution {
        public:
            int compress(vector<char>& chars) {
                int i = 0, res = 0;
                int length = chars.size();
                while (i < length) {
                    int groupLength = 1;
                    while (i + groupLength < length && chars[i + groupLength] == chars[i]) {
                        groupLength++;
                    }
                    chars[res++] = chars[i];
                    if (groupLength > 1) {
                        for (char c : to_string(groupLength)) {
                            chars[res++] = c;
                        }
                    }
                    i += groupLength;
                }
                return res;
            }
        };
        

        4.7.991 - 2023-11-12 15:43:55 +0300 MSK

        Can Place Flowers

        Code

        class Solution {
        public:
            bool canPlaceFlowers(vector<int>& flowerbed, int n) {
                int curZeros = flowerbed[0] == 0 ? 2 : 0;
                int length = flowerbed.size();
                int ans = 0;
                for (int i = 1; i < length; ++i) { 
                    if (flowerbed[i] == 0) {
                        curZeros += 1;
                        continue;
                    }
                    ans += (curZeros - 1) / 2;
                    curZeros = 0;
                    if (ans >= n) {
                        return true;
                    }
                }
                ans += curZeros / 2;
                return ans >= n;
            }
        };
        

        4.7.992 - 2023-11-12 15:41:26 +0300 MSK

        Can Place Flowers

        Code

        class Solution {
        public:
            bool canPlaceFlowers(vector<int>& flowerbed, int n) {
                int curZeros = 0, length = flowerbed.size();
                if (flowerbed[0] == 0) {
                    curZeros = 2;
                }
                int ans = 0;
                for (int i = 1; i < length; ++i) {
                    bool isFlower = flowerbed[i] == 1; 
                    if (!isFlower) {
                        curZeros += 1;
                        continue;
                    }
                    ans += (curZeros - 1) / 2;
                    curZeros = 0;
                    if (ans >= n) {
                        return true;
                    }
                }
                ans += curZeros / 2;
                return ans >= n;
            }
        };
        

        4.7.993 - 2023-11-12 11:40:25 +0300 MSK

        Bus Routes

        Code

        class Solution {
        public:
            int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {
                if (source == target) {
                    return 0;
                }
        
                unordered_map<int, vector<int>> adjList;
                // Create a map from the bus stop to all the routes that include this stop.
                for (int route = 0; route < routes.size(); route++) {
                    for (auto stop : routes[route]) {
                        // Add all the routes that have this stop.
                        adjList[stop].push_back(route);
                    }
                }
        
                queue<int> q;
                unordered_set<int> vis;
                // Insert all the routes in the queue that have the source stop.
                for (auto route : adjList[source]){
                    q.push(route);
                    vis.insert(route);
                }
        
                int busCount = 1;
                while (q.size()) {
                    int size = q.size();
        
                    for (int i = 0; i < size; i++) {
                        int route = q.front(); q.pop();
        
                        // Iterate over the stops in the current route.
                        for (auto stop: routes[route]) {
                            // Return the current count if the target is found.
                            if (stop == target) {
                                return busCount;
                            }
        
                            // Iterate over the next possible routes from the current stop.
                            for (auto nextRoute : adjList[stop]) {
                                if (!vis.count(nextRoute)) {
                                    vis.insert(nextRoute);
                                    q.push(nextRoute);
                                }
                            }
                        }
                    }
                    busCount++;
                }
                return -1;
            }
        };
        

        4.7.994 - 2023-11-11 16:10:00 +0300 MSK

        Fibonacci Number

        Code

        class Solution {
        public:
            int fib(int n) {
                if (n < 2) {
                    return n;
                }
                int cur = 1, prev = 0;
                for (int i = 2; i <= n; ++i) {
                    int newVal = cur + prev;
                    prev = cur;
                    cur = newVal;
                }
                return cur;
            }
        };
        

        4.7.995 - 2023-11-11 16:06:23 +0300 MSK

        Remove Linked List Elements

        Code

        /**
         * Definition for singly-linked list.
         * struct ListNode {
         *     int val;
         *     ListNode *next;
         *     ListNode() : val(0), next(nullptr) {}
         *     ListNode(int x) : val(x), next(nullptr) {}
         *     ListNode(int x, ListNode *next) : val(x), next(next) {}
         * };
         */
        class Solution {
        public:
            ListNode* removeElements(ListNode* head, int val) {
                head = new ListNode(-1, head);
                auto ans = head;
                while (head) {
                    auto next = head->next;
                    if (next && next->val == val) {
                        head->next = next->next;
                    } else {
                        head = next;
                    }
                }
                return ans->next;
            }
        };
        

        4.7.996 - 2023-11-11 16:06:11 +0300 MSK

        Remove Linked List Elements

        Code

        /**
         * Definition for singly-linked list.
         * struct ListNode {
         *     int val;
         *     ListNode *next;
         *     ListNode() : val(0), next(nullptr) {}
         *     ListNode(int x) : val(x), next(nullptr) {}
         *     ListNode(int x, ListNode *next) : val(x), next(next) {}
         * };
         */
        class Solution {
        public:
            ListNode* removeElements(ListNode* head, int val) {
                head = new ListNode(-1, head);
                auto ans = head;
                while (head) {
                    auto next = head->next;
                    if (next && next->val == val) {
                        head->next = next->next;
                    } else {
                        head = head->next;
                    }
                }
                return ans->next;
            }
        };
        

        4.7.997 - 2023-11-11 15:52:58 +0300 MSK

        Valid Parentheses

        Code

        class Solution {
        public:
            bool isValid(string s) {
                std::vector<char> stack;
                for (const auto& ch : s) {
                    switch (ch){
                        case '[':
                        case '{':
                        case '(':
                            stack.push_back(ch);
                            break;
                        case ')':
                            if (stack.empty() || stack.back() != '(') {
                                return false;
                            }
                            stack.pop_back();
                            break;
                        case '}':
                            if (stack.empty() || stack.back() != '{') {
                                return false;
                            }
                            stack.pop_back();
                            break;
                        case ']':
                            if (stack.empty() || stack.back() != '[') {
                                return false;
                            }
                            stack.pop_back();
                            break;
                    }
                }
                return stack.size() == 0;
            }
        };
        

        4.7.998 - 2023-11-11 15:43:36 +0300 MSK

        Two Sum

        Code

        class Solution {
        public:
            vector<int> twoSum(vector<int>& nums, int target) {
                std::map<int, int> numToIndex;
                int length = nums.size();
                std::vector<int> ans;
                for (int i = 0; i < length; ++i) {
                    int num = nums[i];
                    int diff = target - num;
                    if (numToIndex.contains(diff)) {
                        ans = {numToIndex[diff], i};
                        break;
                    }
                    numToIndex[num] = i;
                }
                return ans;
            }
        };
        

        4.7.999 - 2023-11-11 15:32:34 +0300 MSK

        Reverse Words in a String

        Code

        class Solution {
        public:
            string reverseWords(string s) {
                string ans = "";
                string temp = "";
                int length = s.length();
                int j = 0;
                for (j = 0; s[j] == ' ' && j < length; ++j) { }
                for (int i = length - 1; i >= j; --i) {
                    if(s[i] == ' '){
                        if(temp != ""){                  
                            ans = ans + temp + ' ';
                            temp = "";
                        }
                        continue;
                    }
                    else{
                        temp = s[i] + temp;
                    }
                }
                return ans + temp;
            }
        };
        

        4.7.1000 - 2023-11-11 15:18:39 +0300 MSK

        Reverse Linked List

        Code

        
        class Solution {
        public:
            ListNode* reverseList(ListNode* head) {
                ListNode* prev = NULL;
                ListNode* curr = head;
                while(curr != NULL){
                    ListNode* next = curr->next;
                    curr->next = prev;
                    prev = curr;
                    curr = next;
                }
                return prev;
            }
        };
        

        4.7.1001 - 2023-11-11 15:08:55 +0300 MSK

        Move Zeroes

        Code

        class Solution {
        public:
            void moveZeroes(vector<int>& nums) {
                int length = nums.size();
                int lastNonZeroFoundAt = 0;
                for (int i = 0; i < length; ++i) {
                    if (nums[i] != 0) {
                        swap(nums[lastNonZeroFoundAt], nums[i]);
                        lastNonZeroFoundAt += 1;
                    }
                }
            }
        };
        

        4.7.1002 - 2023-11-11 15:06:06 +0300 MSK

        Move Zeroes

        Code

        class Solution {
        public:
            void moveZeroes(vector<int>& nums) {
            int lastNonZeroFoundAt = 0;
            int length = nums.size();
            for (int i = 0; i < length; ++i) {
                int num = nums[i];
                if (num == 0) {
                    continue;
                }
                if (i != lastNonZeroFoundAt) {
                    nums[lastNonZeroFoundAt] = num;
                }
                lastNonZeroFoundAt += 1;
            }
         	for (int i = lastNonZeroFoundAt; i < length; i++) {
                nums[i] = 0;
            }
        }
        };
        

        4.7.1003 - 2023-11-11 14:51:09 +0300 MSK

        Design Graph With Shortest Path Calculator

        Code

        class Graph {
        public:
            vector<vector<pair<int, int>>> adjList;
            Graph(int n, vector<vector<int>>& edges) {
                adjList.resize(n);
                for (auto& e: edges)
                    adjList[e[0]].push_back(make_pair(e[1], e[2]));
            }
        
            void addEdge(vector<int> edge) {
                adjList[edge[0]].push_back(make_pair(edge[1], edge[2]));
            }
        
            int shortestPath(int node1, int node2) {
                int n = adjList.size();
                priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;
                vector<int> costForNode(n, INT_MAX);
                costForNode[node1] = 0;
                pq.push({0, node1});
        
                while (!pq.empty()) {
                    int currCost = pq.top()[0];
                    int currNode = pq.top()[1];
                    pq.pop();
        
                    if (currCost > costForNode[currNode]) {
                        continue;
                    }
                    if (currNode == node2) {
                        return currCost;
                    }
                    for (auto& neighbor : adjList[currNode]) {
                        int neighborNode = neighbor.first;
                        int cost = neighbor.second;
                        int newCost = currCost + cost;
        
                        if (newCost < costForNode[neighborNode]) {
                            costForNode[neighborNode] = newCost;
                            pq.push({newCost, neighborNode});
                        }
                    }
                }
                return -1;
            }
        };
        

        4.7.1004 - 2023-11-10 19:50:03 +0300 MSK

        Merge Strings Alternately

        Code

        class Solution {
        public:
            string mergeAlternately(string word1, string word2) {
                int m = word1.size();
                int n = word2.size();
                string result = "";
        
                for (int i = 0; i < max(m, n); i++) {
                    if (i < m) {
                        result.push_back(word1[i]);
                    }
                    if (i < n) {
                        result.push_back(word2[i]);
                    }
                }
        
                return result;
            }
        };
        

        4.7.1005 - 2023-11-10 19:49:28 +0300 MSK

        Merge Strings Alternately

        Code

        class Solution {
        public:
            string mergeAlternately(string word1, string word2) {
                int l1 = word1.size(), l2 = word2.size();
                string result = "";
                int i = 0, j = 0;
                while (i < l1 || j < l2) {
                    if (i < l1) {
                        result.push_back(word1[i++]);
                    }
                    if (j < l2) {
                        result.push_back(word2[j++]);
                    }
                }
                return result;
            }
        };
        

        4.7.1006 - 2023-11-10 19:47:59 +0300 MSK

        Merge Strings Alternately

        Code

        class Solution {
        public:
            string mergeAlternately(string word1, string word2) {
                std::stringstream ans;
                int l1 = word1.size(), l2 = word2.size();
                int lMax = max(l1, l2);
                for (int i = 0; i < lMax; ++i) {
                    if (i < l1) {
                        ans << word1[i];
                    } else {
                        ans << word2.substr(i);
                        break;
                    }
                    if (i < l2) {
                        ans << word2[i];
                    } else {
                        ans << word1.substr(i + 1);
                        break;
                    }
                }
                return ans.str();
            }
        };
        

        4.7.1007 - 2023-11-10 19:34:50 +0300 MSK

        Subrectangle Queries

        Code

        class SubrectangleQueries {
            vector<vector<int>> res;
        public:
            SubrectangleQueries(vector<vector<int>>& rectangle) {
                res=rectangle;
            }
            
            void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
                for(int i = row1; i <= row2; ++i) {
                    for(int j= col1; j <= col2; ++j) {
                        res[i][j] = newValue;
                    }
                }
            }
            
            int getValue(int row, int col) {
                return res[row][col];
            }
        };
        
        /**
         * Your SubrectangleQueries object will be instantiated and called as such:
         * SubrectangleQueries* obj = new SubrectangleQueries(rectangle);
         * obj->updateSubrectangle(row1,col1,row2,col2,newValue);
         * int param_2 = obj->getValue(row,col);
         */
        

        4.7.1008 - 2023-11-10 19:18:28 +0300 MSK

        Subrectangle Queries

        Code

        class SubrectangleQueries {
        public:
            std::vector<std::vector<int>> rectangle;
            std::vector<std::array<int, 5>> updates;
            SubrectangleQueries(vector<vector<int>>& rectangle) {
                this->rectangle = rectangle;
            }
            
            void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
                this->updates.push_back({row1, col1, row2, col2, newValue});
            }
            
            int getValue(int row, int col) {
                int length = this->updates.size();
                for (int i = length - 1; i >= 0; --i) {
                    auto const [row1, col1, row2, col2, newValue] = this->updates[i];
                    if (row < row1 || row > row2 || col < col1 || col > col2) {
                        continue;
                    }
                    return newValue;
                }
                return this->rectangle[row][col];
            }
        };
        
        /**
         * Your SubrectangleQueries object will be instantiated and called as such:
         * SubrectangleQueries* obj = new SubrectangleQueries(rectangle);
         * obj->updateSubrectangle(row1,col1,row2,col2,newValue);
         * int param_2 = obj->getValue(row,col);
         */
        

        4.7.1009 - 2023-11-10 18:37:59 +0300 MSK

        Operations on Tree

        Code

        class LockingTree {
        public:
            std::vector<int> parents, locked;
            std::vector<std::vector<int>> children;
            LockingTree(vector<int>& parent) {
                int length = parent.size();
                this->children.resize(length);
                this->locked.resize(length, -1);
                this->parents = parent;
                for (int i = 1; i < length; ++i) {
                    this->children[this->parents[i]].push_back(i);
                }
            }
            
            bool lock(int num, int user) {
                if (this->locked[num] != -1) {
                    return false;
                }
                this->locked[num] = user;
                return true;
            }
            
            bool unlock(int num, int user) {
                if (this->locked[num] != user) {
                    return false;
                }
                this->locked[num] = -1;
                return true;
            }
        
            bool upgrade(int num, int user) {
                if (this->locked[num] != -1) {
                    return false;
                }
                int parent = this->parents[num];
                while (parent != -1) {
                    if (this->locked[parent] != -1) {
                        return false;
                    }
                    parent = this->parents[parent];
                }
                if (!this->unlockDesc(num)) {
                    return false;
                }
                this->locked[num] = user;
                return true;
            }
        
            bool unlockDesc(int parent) {
                bool hasLocked = false;
                for (auto const& child : this->children[parent]) {
                    if (this->locked[child] != -1) {
                        this->locked[child] = -1;
                        hasLocked = true;
                    }
                    bool descHasLocked = unlockDesc(child);
                    if (descHasLocked) {
                        hasLocked = true;
                    }
                }
                return hasLocked;
            }
        };
        
        /**
         * Your LockingTree object will be instantiated and called as such:
         * LockingTree* obj = new LockingTree(parent);
         * bool param_1 = obj->lock(num,user);
         * bool param_2 = obj->unlock(num,user);
         * bool param_3 = obj->upgrade(num,user);
         */
        

        4.7.1010 - 2023-11-10 16:30:33 +0300 MSK

        Implement Stack using Queues

        Code

        class MyStack {
        public:
            std::vector<int> v;
        
            MyStack() {
                this->v = {};
            }
            
            void push(int x) {
                this->v.push_back(x);
            }
            
            int pop() {
                int last = this->v.back();
                this->v.pop_back();
                return last;
            }
            
            int top() {
                return this->v.back();
            }
            
            bool empty() {
                return this->v.empty();
            }
        };
        
        /**
         * Your MyStack object will be instantiated and called as such:
         * MyStack* obj = new MyStack();
         * obj->push(x);
         * int param_2 = obj->pop();
         * int param_3 = obj->top();
         * bool param_4 = obj->empty();
         */
        

        4.7.1011 - 2023-11-10 13:30:38 +0300 MSK

        Restore the Array From Adjacent Pairs

        Code

        func restoreArray(adjacentPairs [][]int) []int {
            // [[2,1],[3,4],[3,2]]
            // 1: [2]
            // 2: [1, 3]
            // 3: [2, 4]
            // 4: [3]
            // Output: [1,2,3,4]
            graph := map[int][]int{}
            length := len(adjacentPairs) + 1
            ans := make([]int, length)
            for _, pair := range adjacentPairs {
                num1, num2 := pair[0], pair[1]
                graph[num1] = append(graph[num1], num2)
                graph[num2] = append(graph[num2], num1)
            }
            for node, edges := range graph {
                if len(edges) == 1 {
                    ans[0], ans[1] = node, edges[0]
                    break
                }
            }
            cur, prev := ans[1], ans[0]
            for i := 2; i < length; i++ {
                for _, target := range graph[cur] {
                    if target != prev {
                        ans[i] = target
                        cur, prev = target, cur
                        break
                    }
                }
            }
            return ans
        }
        

        4.7.1012 - 2023-11-10 13:24:56 +0300 MSK

        Restore the Array From Adjacent Pairs

        Code

        func restoreArray(adjacentPairs [][]int) []int {
            // [[2,1],[3,4],[3,2]]
            // 1: [2]
            // 2: [1, 3]
            // 3: [2, 4]
            // 4: [3]
            // Output: [1,2,3,4]
            graph := map[int][]int{}
            for _, pair := range adjacentPairs {
                num1, num2 := pair[0], pair[1]
                graph[num1] = append(graph[num1], num2)
                graph[num2] = append(graph[num2], num1)
            }
            length := len(adjacentPairs) + 1
            ans := make([]int, length)
            for node, edges := range graph {
                if len(edges) == 1 {
                    ans[0], ans[1] = node, edges[0]
                    break
                }
            }
            for i := 2; i < length; i++ {
                cur, prev := ans[i-1], ans[i-2]
                for _, target := range graph[cur] {
                    if target != prev {
                        ans[i] = target
                    }
                }
            }
            return ans
        }
        

        4.7.1013 - 2023-11-09 10:03:41 +0300 MSK

        Count Number of Homogenous Substrings

        Code

        func countHomogenous(s string) int {
            var (
                mod int64 = 1000000007 
                total int64 = 0
                count int64 = 0
                cur = s[0]
            )
            
            for i := 0; i < len(s); i++ {
                char := s[i]
                if char == cur {
                    count++
                } else {
                    count = 1
                    cur = char
                }
                total += count
            }
            
            return int(total % mod)
        }
        

        4.7.1014 - 2023-11-08 11:09:02 +0300 MSK

        Determine if a Cell Is Reachable at a Given Time

        Code

        func isReachableAtTime(sx int, sy int, fx int, fy int, t int) bool {
            vert := abs(sy, fy)
            dist := vert + max(0, abs(sx, fx) - vert)
            if dist == 0 && t == 1 {
                return false
            }
            return dist <= t
        }
        
        func abs(x, y int) int {
            if x > y {
                return x - y
            }
            return y - x
        }
        

        4.7.1015 - 2023-11-07 21:56:45 +0300 MSK

        Design HashSet

        Code

        type MyHashSet struct {
            m map[int]struct{}
        }
        
        
        func Constructor() MyHashSet {
            return MyHashSet{map[int]struct{}{}}
        }
        
        
        func (this *MyHashSet) Add(key int)  {
            this.m[key] = struct{}{}
        }
        
        
        func (this *MyHashSet) Remove(key int)  {
            delete(this.m, key)
        }
        
        
        func (this *MyHashSet) Contains(key int) bool {
            _, ok := this.m[key]
            return ok
        }
        
        
        /**
         * Your MyHashSet object will be instantiated and called as such:
         * obj := Constructor();
         * obj.Add(key);
         * obj.Remove(key);
         * param_3 := obj.Contains(key);
         */
        

        4.7.1016 - 2023-11-07 21:50:49 +0300 MSK

        Merge Strings Alternately

        Code

        func mergeAlternately(word1 string, word2 string) string {
            var sb strings.Builder
            length1, length2 := len(word1), len(word2)
            for i := 0; i < max(length1, length2); i++ {
                if i == length1 {
                    sb.WriteString(word2[i:length2])
                    break
                }
                if i == length2 {
                    sb.WriteString(word1[i:length1])
                    break
                }
                sb.WriteByte(word1[i])
                sb.WriteByte(word2[i])
            }
            return sb.String()
        }
        

        4.7.1017 - 2023-11-07 19:07:48 +0300 MSK

        Eliminate Maximum Number of Monsters

        Code

        func eliminateMaximum(dist []int, speed []int) int {
            arrival := []float32{}
            length := len(dist)
            for i := 0; i < length; i++ {
                arrival = append(arrival, float32(dist[i]) / float32(speed[i]))
            }
            slices.Sort(arrival)
            ans := 0
            for i := 0; i < length; i++ {
                if arrival[i] <= float32(i) {
                    break
                }
                ans += 1
            }
            return ans
        }
        

        4.7.1018 - 2023-11-06 18:41:34 +0300 MSK

        Design Circular Deque

        Code

        type MyCircularDeque struct {
            list []int
            size int
        }
        
        
        func Constructor(k int) MyCircularDeque {
            return MyCircularDeque{[]int{}, k}
        }
        
        
        func (this *MyCircularDeque) InsertFront(value int) bool {
            if this.IsFull() {
                return false
            }
            this.list = append([]int{value}, this.list...)
            return true
        }
        
        
        func (this *MyCircularDeque) InsertLast(value int) bool {
            if this.IsFull() {
                return false
            }
            this.list = append(this.list, value)
            return true
        }
        
        
        func (this *MyCircularDeque) DeleteFront() bool {
            if this.IsEmpty() {
                return false
            }
            this.list = this.list[1:]
            return true
        }
        
        
        func (this *MyCircularDeque) DeleteLast() bool {
            if this.IsEmpty() {
                return false
            }
            this.list = this.list[:len(this.list) - 1]
            return true
        }
        
        
        func (this *MyCircularDeque) GetFront() int {
            if this.IsEmpty() {
                return -1
            }
            return this.list[0]   
        }
        
        
        func (this *MyCircularDeque) GetRear() int {
            if this.IsEmpty() {
                return -1
            }
            return this.list[len(this.list) - 1]
        }
        
        
        func (this *MyCircularDeque) IsEmpty() bool {
            return len(this.list) == 0
        }
        
        
        func (this *MyCircularDeque) IsFull() bool {
            return len(this.list) == this.size
        }
        
        
        /**
         * Your MyCircularDeque object will be instantiated and called as such:
         * obj := Constructor(k);
         * param_1 := obj.InsertFront(value);
         * param_2 := obj.InsertLast(value);
         * param_3 := obj.DeleteFront();
         * param_4 := obj.DeleteLast();
         * param_5 := obj.GetFront();
         * param_6 := obj.GetRear();
         * param_7 := obj.IsEmpty();
         * param_8 := obj.IsFull();
         */
        

        4.7.1019 - 2023-11-06 14:57:33 +0300 MSK

        Seat Reservation Manager

        Code

        type SeatManager struct {
            heap *binaryheap.Heap
        }
        
        
        func Constructor(n int) SeatManager {
            heap := binaryheap.NewWithIntComparator()
            for i := 1; i <= n; i++ {
                heap.Push(i)
            }
            return SeatManager{heap}
        }
        
        
        func (this *SeatManager) Reserve() int {
            val, _ := this.heap.Pop()
            return val.(int)
        }
        
        
        func (this *SeatManager) Unreserve(seatNumber int)  {
            this.heap.Push(seatNumber)
        }
        
        
        /**
         * Your SeatManager object will be instantiated and called as such:
         * obj := Constructor(n);
         * param_1 := obj.Reserve();
         * obj.Unreserve(seatNumber);
         */
        

        4.7.1020 - 2023-11-06 14:49:27 +0300 MSK

        Seat Reservation Manager

        Code

        type SeatManager struct {
            seats []bool
        }
        
        
        func Constructor(n int) SeatManager {
            return SeatManager{make([]bool, n)}
        }
        
        
        func (this *SeatManager) Reserve() int {
            for i, num := range this.seats {
                if !num {
                    this.seats[i] = true
                    return i + 1
                }
            }
            return -1
        }
        
        
        func (this *SeatManager) Unreserve(seatNumber int)  {
            this.seats[seatNumber-1] = false
        }
        
        
        /**
         * Your SeatManager object will be instantiated and called as such:
         * obj := Constructor(n);
         * param_1 := obj.Reserve();
         * obj.Unreserve(seatNumber);
         */
        

        4.7.1021 - 2023-11-05 21:02:40 +0300 MSK

        Serialize and Deserialize Binary Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        
        type Codec struct {
            
        }
        
        func Constructor() Codec {
            return Codec{}
        }
        
        // Serializes a tree to a single string.
        func (this *Codec) serialize(root *TreeNode) string {
            if root == nil {
                return ""
            }
            var buffer bytes.Buffer
            queue := []*TreeNode{root}
            for length := len(queue); length > 0; length = len(queue) {
                for i := 0; i < length; i++ {
                    node := queue[i]
                    if node != nil {
                        buffer.WriteString(strconv.Itoa(node.Val))
                        queue = append(queue, node.Left, node.Right)
                    }
                    buffer.WriteString(",")
                }
                queue = queue[length:]
            }
            ans := buffer.String()
            return ans[:len(ans)-1]
        }
        
        // Deserializes your encoded data to tree.
        func (this *Codec) deserialize(data string) *TreeNode {    
            nodes := []*TreeNode{}
            for _, str := range strings.Split(data, ",") {
                if str == "" {
                    nodes = append(nodes, nil)
                } else {
                    num, _ := strconv.Atoi(str)
                    nodes = append(nodes, &TreeNode{num, nil, nil})
                }
            }
            start := 0
            length := len(nodes)
            for _, node := range nodes {
                if node == nil {
                    continue
                }
                left, right := 2 * start + 1, 2 * start + 2
                if left < length {
                    node.Left = nodes[left]
                }
                if right < length {
                    node.Right = nodes[right]
                }
                start++
            }
            return nodes[0]
        }
        
        
        /**
         * Your Codec object will be instantiated and called as such:
         * ser := Constructor();
         * deser := Constructor();
         * data := ser.serialize(root);
         * ans := deser.deserialize(data);
         */
        

        4.7.1022 - 2023-11-05 12:06:04 +0300 MSK

        Find the Winner of an Array Game

        Code

        func getWinner(arr []int, k int) int {
            if k == 1 {
                return max(arr[0], arr[1])
            }
            length := len(arr)
            if k >= length {
                return slices.Max(arr)
            }
            curWinner, winCount := arr[0], 0
            for _, num := range arr[1:] {
                if curWinner > num {
                    winCount++
                } else {
                    curWinner = num
                    winCount = 1
                }
                if winCount == k {
                    return curWinner
                }
            }
            return curWinner
        }
        

        4.7.1023 - 2023-11-05 12:01:59 +0300 MSK

        Find the Winner of an Array Game

        Code

        func getWinner(arr []int, k int) int {
            curMax, winCount := arr[0], 0
            i, length := 1, len(arr)
            for {
                num := arr[i]
                if num > curMax {
                    curMax = num
                    winCount = 1
                } else {
                    winCount++
                }
                if winCount == k {
                    return curMax
                }
                i = (i + 1) % length
            }
            return -1
        }
        

        4.7.1024 - 2023-11-04 13:31:04 +0300 MSK

        Find Median from Data Stream

        Code

        type MaxHeap []int
        func (m MaxHeap) Len() int { return len(m) }
        func (m MaxHeap) Less(i, j int) bool { return m[i] > m[j] }
        func (m MaxHeap) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
        func (m *MaxHeap) Pop() interface{} {
            v := (*m)[len(*m)-1]
            *m = (*m)[:len(*m)-1]
            return v
        }
        func (m *MaxHeap) Push(v interface{}) { *m = append(*m, v.(int)) }
        func (m MaxHeap) Top() int { return m[0] }
        
        type MinHeap []int
        func (m MinHeap) Len() int { return len(m) }
        func (m MinHeap) Less(i, j int) bool { return m[i] < m[j] }
        func (m MinHeap) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
        func (m *MinHeap) Pop() interface{} {
            v := (*m)[len(*m)-1]
            *m = (*m)[:len(*m)-1]
            return v
        }
        func (m *MinHeap) Push(v interface{}) { *m = append(*m, v.(int)) }
        func (m MinHeap) Top() int { return m[0] }
        
        type MedianFinder struct {
            left MaxHeap
            right MinHeap    
        }
        
        func Constructor() MedianFinder {
            return MedianFinder{}    
        }
        
        func (mf *MedianFinder) AddNum(num int)  {
            if len(mf.left) + len(mf.right) == 0 {
                heap.Push(&(mf.left), num)
                return
            }
            for {
                if len(mf.left) < len(mf.right) {
                    if num <= mf.right.Top() {
                        heap.Push(&(mf.left), num)
                        return
                    } else {
                        v := heap.Pop(&(mf.right))
                        heap.Push(&(mf.left), v)
                    }
                } else {
                    if num >= mf.left.Top() {
                        heap.Push(&(mf.right), num)
                        return
                    } else {
                        v := heap.Pop(&(mf.left))
                        heap.Push(&(mf.right), v)
                    }
                }
            }
        }
        
        func (mf *MedianFinder) FindMedian() float64 {
            if len(mf.left) == len(mf.right) {
                return float64(mf.left.Top() + mf.right.Top()) / 2.0
            } else if len(mf.left) > len(mf.right) {
                return float64(mf.left.Top())
            } else {
                return float64(mf.right.Top())
            }   
        }
        

        4.7.1025 - 2023-11-04 13:30:46 +0300 MSK

        IPO

        Code

        type Project struct {
            profit, capital int
        }
        
        type IntHeap []int
        func (h IntHeap) Len() int           { return len(h) }
        func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
        func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
        func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
        func (h *IntHeap) Pop() interface{} {
        	old := *h
        	n := len(old)
        	x := old[n-1]
        	*h = old[0 : n-1]
        	return x
        }
        
        func findMaximizedCapital(k int, w int, profits []int, capital []int) int {
            n := len(profits)
            projects := make([]Project, n)
            for i := range profits {
                projects[i] = Project{profits[i], capital[i]}
            }
            sort.Slice(projects, func (i, j int) bool {
                return projects[i].capital < projects[j].capital
            })
            
            q := &IntHeap{}
            heap.Init(q)
        
            ptr := 0
            for i := 0; i < k; i++ {
                for ptr < n && projects[ptr].capital <= w {
                    heap.Push(q, projects[ptr].profit)
                    ptr++
                }
                if q.Len() == 0 {
                    break
                }
                w += heap.Pop(q).(int)
            }
            return w
        }
        

        4.7.1026 - 2023-11-04 13:30:28 +0300 MSK

        Find Peak Element

        Code

        func findPeakElement(nums []int) int {
            left := 0
            right := len(nums) - 1
            
            for left < right {
                mid := left + (right - left) / 2
                
                if nums[mid] > nums[mid+1] {
                    // The peak is in the left half
                    right = mid
                } else {
                    // The peak is in the right half
                    left = mid + 1
                }
            }
            
            return left
        }
        

        4.7.1027 - 2023-11-04 13:30:08 +0300 MSK

        Merge k Sorted Lists

        Code

        /**
         * Definition for singly-linked list.
         * type ListNode struct {
         *     Val int
         *     Next *ListNode
         * }
         */
        func mergeKLists(lists []*ListNode) *ListNode {
            n:=len(lists)
            if n==0{
                return nil
            }
            curr:=lists[0]
            if n==1{
                return curr
            }
            for i:=1;i<n;i++{
                curr=mergeList(curr,lists[i])
            }
            return curr
        }
        
        func mergeList(l1,l2 *ListNode) *ListNode {
            head:=&ListNode{}
            curr:=head
            for l1!=nil && l2!=nil{
                if l1.Val<l2.Val{
                    curr.Next=l1
                    l1=l1.Next
                    curr=curr.Next
                }else{
                    curr.Next=l2
                    l2=l2.Next
                    curr=curr.Next
                }
            }
            if l1 != nil {
                curr.Next = l1
            } else if l2 != nil {
                curr.Next = l2
            }
            return head.Next
        }
        

        4.7.1028 - 2023-11-04 13:29:52 +0300 MSK

        Construct Quad Tree

        Code

        /**
         * Definition for a QuadTree node.
         * type Node struct {
         *     Val bool
         *     IsLeaf bool
         *     TopLeft *Node
         *     TopRight *Node
         *     BottomLeft *Node
         *     BottomRight *Node
         * }
         */
        
        func construct(grid [][]int) *Node {
        	var dfs func(y0, x0, width int) *Node
        	dfs = func(y0, x0, width int) *Node {
        		if width == 1 {
        			return &Node{
        				Val:    grid[y0][x0] == 1,
        				IsLeaf: true,
        			}
        		}
        
        		w := width / 2
        		topLeft := dfs(y0, x0, w)
        		topRight := dfs(y0, x0+w, w)
        		bottomLeft := dfs(y0+w, x0, w)
        		bottomRight := dfs(y0+w, x0+w, w)
        		var node *Node
        
        		if topLeft.Val == topRight.Val && bottomLeft.Val == bottomRight.Val && topLeft.Val == bottomLeft.Val &&
        			topLeft.IsLeaf && topRight.IsLeaf && bottomLeft.IsLeaf && bottomRight.IsLeaf {
        			node = &Node{
        				Val:    topLeft.Val,
        				IsLeaf: true,
        			}
        		} else {
        			node = &Node{
        				Val:         true,
        				IsLeaf:      false,
        				TopLeft:     topLeft,
        				TopRight:    topRight,
        				BottomLeft:  bottomLeft,
        				BottomRight: bottomRight,
        			}
        		}
        		return node
        	}
        	return dfs(0, 0, len(grid))
        }
        

        4.7.1029 - 2023-11-04 13:29:35 +0300 MSK

        N-Queens II

        Code

        func totalNQueens(n int) int {
            sCol:=make([]bool,n)
            sD1:=make([]bool,2*n)
            sD2:=make([]bool,2*n)
            return helper(0,n,sCol,sD1,sD2)
        }
        func helper(r,n int,sCol,sD1,sD2 []bool) int{
            if r==n{
                return 1
            }
            res:=0
            for i:=0; i < n; i++ {
                if !sCol[i] && !sD1[i+r] && !sD2[(r-i)+n]{
                  // board[r][i]=true
                    sCol[i]=true
                    sD1[i+r]=true
                    sD2[(r-i)+n]=true
                    res=res+helper(r+1,n,sCol,sD1,sD2)
                  //  board[r][i]=false
                    sCol[i]=false
                    sD1[i+r]=false
                    sD2[(r-i)+n]=false
                }
            }
            return res
        }
        

        4.7.1030 - 2023-11-04 13:29:17 +0300 MSK

        Word Search II

        Code

        type Node struct {
        	children [26]*Node
        	word     string
        }
        
        func (n *Node) Insert(word string) {
        	cur := n
        	for _, c := range word {
        		idx := c - 'a'
        		if cur.children[idx] == nil {
        			cur.children[idx] = &Node{}
        		}
        		cur = cur.children[idx]
        	}
        	cur.word = word
        }
        
        func (n *Node) IsEmpty() bool {
        	for _, child := range n.children {
        		if child != nil {
        			return false
        		}
        	}
        	return true
        }
        
        func (n *Node) Remove(word string) bool {
        	if len(word) == 0 {
        		n.word = ""
        		return n.IsEmpty()
        	}
        	child := n.children[word[0]-'a']
        	if child.Remove(word[1:]) {
        		n.children[word[0]-'a'] = nil
        		return n.IsEmpty()
        	}
        	return false
        }
        
        func dfs(board [][]byte, r, c int, root, cur *Node, res *[]string) {
        	rc := board[r][c]
        	board[r][c] = 0
            
        	if cur.word != "" {
        		*res = append(*res, cur.word)
        		root.Remove(cur.word)
        	}
        	ds := [5]int{0, 1, 0, -1, 0}
        	for i := 0; i < len(ds)-1; i++ {
        		dr, dc := r+ds[i], c+ds[i+1]
        		if dr < 0 || dr >= len(board) || dc < 0 || dc >= len(board[0]) {
        			continue
        		}
        		b := board[dr][dc]
        		if b == 0 || cur.children[b-'a'] == nil {
        			continue
        		}
        		dfs(board, dr, dc, root, cur.children[b-'a'], res)
        	}
        	board[r][c] = rc
        }
        
        func findWords(board [][]byte, words []string) []string {
        	m, n := len(board), len(board[0])
        	res, trie, has := []string{}, &Node{}, map[string]bool{}
        
        	for r := 0; r < m; r++ {
        		for c := 0; c < n-1; c++ {
        			p := string(board[r][c]) + string(board[r][c+1])
        			has[p] = true
        		}
        	}
        	for r := 0; r < m-1; r++ {
        		for c := 0; c < n; c++ {
        			p := string(board[r][c]) + string(board[r+1][c])
        			has[p] = true
        		}
        	}
        	for _, word := range words {
        		valid := true
        		for i := 0; i < len(word)-1; i++ {
        			a, b := string(word[i]), string(word[i+1])
        			if !has[a+b] && !has[b+a] {
        				valid = false
        				break
        			}
        		}
        		if valid {
        			trie.Insert(word)
        		}
        	}
        	for r := 0; r < m; r++ {
        		for c := 0; c < n; c++ {
        			b := board[r][c]
        			if trie.children[b-'a'] != nil {
        				dfs(board, r, c, trie, trie.children[b-'a'], &res)
        			}
        		}
        	}
        	return res
        }
        

        4.7.1031 - 2023-11-04 13:28:50 +0300 MSK

        Word Ladder

        Code

        func ladderLength(beginWord string, endWord string, wordList []string) int {
            
            set := make(map[string]struct{}, len(wordList))
            
            present := false
            
            for _, v := range wordList {
                if endWord == v {
                    present = true
                } 
                
                set[v] = struct{}{} 
            }
            
            if !present {
                return 0
            }
            
            set[beginWord] = struct{}{}
            q := []string{beginWord}
            
            depth := 1
            breadth := 0
            
            breadth = len(q)
            
            for ;breadth > 0; {
                s := q[0]
                
                if s == endWord {
                    return depth
                }
                
                for i:='a'; i <= 'z'; i += 1 {
                                
                    for j := 0; j<len(s); j++ {
         
                        if rune(s[j]) != i {
                            
                            temp := s[:j] + string(i) + s[j+1:]
                            if _, ok := set[temp]; !ok {
                                continue
                            }
                            
                            q = append(q, temp)
                            delete(set, s)
                        }
                    }
                }
                
                q = q[1:]
                
                breadth -= 1
                if breadth == 0 {
                    breadth = len(q)
                    depth += 1
                }
            }
            
            return 0 
        }
        

        4.7.1032 - 2023-11-04 13:28:04 +0300 MSK

        Course Schedule II

        Code

        func findOrder(numCourses int, prerequisites [][]int) []int {
            //build the graph
            graph := make([][]int,numCourses)
            in_degree := make([]int,numCourses)
            for _,v := range prerequisites{
                graph[v[1]] = append(graph[v[1]], v[0])
                in_degree[v[0]]++
            }
        
            frontier := []int{}
            for i,v := range in_degree{
                if v==0{
                    frontier = append(frontier,i)
                }
            }
        
            result := []int{}
            for len(frontier)!=0{
                cur := frontier[0]
                frontier = frontier[1:]
                result = append(result,cur)
                for _,v := range graph[cur]{
                    in_degree[v]--
                    if in_degree[v]==0{
                        frontier = append(frontier,v)
                    }
                }
            }
        
            if len(result)==numCourses{
                return result
            }
            return []int{}
        }
        

        4.7.1033 - 2023-11-04 13:27:48 +0300 MSK

        Binary Tree Maximum Path Sum

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func maxPathSum(root *TreeNode) int {
            ans := -1 << 63
            maxPath(root, &ans)
            return ans
        }
        
        func maxPath(root *TreeNode, ans *int) int {
            if root == nil {
                return 0
            }
            leftPathSum := maxPath(root.Left, ans)
            rightPathSum := maxPath(root.Right, ans)
            *ans = max(*ans, leftPathSum + rightPathSum + root.Val)
            return max(max(leftPathSum+root.Val, rightPathSum+root.Val), 0)
        }
        
        func max(a int, b int) int {
            if (a >= b) {
                return a
            }
            return b
        }
        

        4.7.1034 - 2023-11-04 13:27:29 +0300 MSK

        Construct Binary Tree from Inorder and Postorder Traversal

        Code

        func buildTree(inorder []int, postorder []int) *TreeNode {
        	n := len(postorder)
        	if n == 0 {
        		return nil
        	}
        
        	pivotId := 0
        	for pivotId < n && inorder[pivotId] != postorder[n-1] {
        		pivotId++
        	}
        
        	root := new(TreeNode)
        	root.Val = postorder[n-1]
        	root.Left = buildTree(inorder[:pivotId], postorder[:pivotId])
        	root.Right = buildTree(inorder[pivotId+1:], postorder[pivotId:n-1])
        	return root
        }
        

        4.7.1035 - 2023-11-04 13:27:12 +0300 MSK

        Construct Binary Tree from Preorder and Inorder Traversal

        Code

        func buildTree(preorder []int, inorder []int) *TreeNode {
        	n := len(inorder)
        
        	if n == 0 {
        		return nil
        	}
        
        	pv := preorder[0]
        	pi := 0
        	for pi < n && inorder[pi] != pv {
        		pi++
        	}
        
        	ans := new(TreeNode)
        	ans.Val = pv
        	ans.Left = buildTree(preorder[1:], inorder[:pi])
        	ans.Right = buildTree(preorder[1+pi:], inorder[pi+1:])
        
        	return ans
        }
        

        4.7.1036 - 2023-11-04 13:26:43 +0300 MSK

        Reverse Nodes in k-Group

        Code

        func reverseKGroup(head *ListNode, k int) *ListNode {
        	node, cnt := head, 0
        	for cnt < k {
        		if node == nil {
        			return head
        		}
        		node = node.Next
        		cnt++
        	}
        
        	prev := reverseKGroup(node, k)
        	for cnt > 0 {
        		next := head.Next
        		head.Next = prev
        		prev = head
        		head = next
        		cnt--
        	}
        
        	return prev
        }
        

        4.7.1037 - 2023-11-04 13:25:42 +0300 MSK

        Minimum Number of Arrows to Burst Balloons

        Code

        func findMinArrowShots(points [][]int) int {
        	// greedy solution
        	sort.Slice(points, func(i, j int) bool {
        		return points[i][1] < points[j][1]
        	})
        	count := 1
        	end := points[0][1]
        	for i := 1; i < len(points); i++ {
        		if points[i][0] > end {
        			count++
        			end = points[i][1]
        		}
        	}
        	return count
        }
        

        4.7.1038 - 2023-11-04 13:25:15 +0300 MSK

        Minimum Window Substring

        Code

        func minWindow(s string, t string) string {
            m := len(s)
            n := len(t)
            
            if m == 0 || n == 0 || m < n {
                return ""
            }
        
            dict := make(map[byte]int)
            for i := 0; i < n; i++ {
                dict[t[i]]++
            }
            
            // required unique chars
            required := len(dict)
            actual := 0
            window := make(map[byte]int)
            minSize := math.MaxInt64
            start := 0
            left, right := 0, 0
            
            for end := 0; end < m; end++ {
                c := s[end]
                window[c]++
                
                if value, ok := dict[c]; ok {
                    if value == window[c] {
                        actual++
                    }
                }
                
                for start <= end && actual == required {
                    size := end-start+1
                    if size < minSize {
                        minSize = size
                        left = start
                        right = end
                    }
                    
                    rc := s[start]
                    window[rc]--
                    if value, ok := dict[rc]; ok {
                        if value > window[rc] {
                            actual--
                        }
                    }
                    start++
                }
            }
            
            if minSize == math.MaxInt64 {
                return ""
            }
            return s[left:right+1]
        }
        

        4.7.1039 - 2023-11-04 13:24:58 +0300 MSK

        Substring with Concatenation of All Words

        Code

        func findSubstring(s string, words []string) []int {
            
            wordLen := len(words[0])
            totalWords := len(words)
            mem := make(map[string]int, totalWords)
            
            
            for _, str := range words {
                mem[str] += 1
            }
            
            temp := make(map[string]int, totalWords)
            var found bool
            result := make([]int, 0)
            
            for i:=0; i + wordLen*totalWords <= len(s);  {
                    
                found = true
                temp = make(map[string]int, totalWords)
        
                for j := i; j < i + wordLen*totalWords; j += wordLen {
                    if _, ok := mem[ s[j:j+wordLen] ]; ok {
                        temp[ s[j:j+wordLen] ] += 1
                    } else {
                        found = false
                        break
                    }
                }
        
                if found {
                    for key, _ := range mem {
                        if val, ok := temp[key]; !ok || val != mem[key]{
                            i++
                            found = false
                            break
                        }
                    }
        
                    if found {
                        result = append(result, i)
                        i += 1    
                    }
        
                } else {
                    i++
                }
            }
            
            return result
            
        }
        

        4.7.1040 - 2023-11-04 13:23:30 +0300 MSK

        Insert Interval

        Code

        func insert(intervals [][]int, new []int) [][]int {
            n := len(intervals)
            i := sort.Search(n, func(i int) bool { return intervals[i][0] > new[0] })
            j := sort.Search(n, func(j int) bool { return intervals[j][1] > new[1] })
            if i >= 1 && new[0] <= intervals[i-1][1] {
                new[0] = intervals[i-1][0]
                i--
            }
            if j < n && new[1] >= intervals[j][0] {
                new[1] = intervals[j][1]
                j++
            }
            return append(intervals[:i], append([][]int{new}, intervals[j:]...)...)
        }
        

        4.7.1041 - 2023-11-04 13:22:41 +0300 MSK

        Basic Calculator

        Code

        func calculate(s string) int {
        	result, _ := calculateFrom(s, 0)
        	return result
        }
        
        func calculateFrom(s string, idFrom int) (result, idEnd int) {
        	result, currNum, sign := 0, 0, 1
        
        	for idEnd = idFrom; idEnd < len(s) && s[idEnd] != ')'; idEnd++ {
        		switch {
        		case s[idEnd] >= '0':
        			currNum = currNum*10 + int(s[idEnd]-'0')
        		case s[idEnd] == '(':
        			currNum, idEnd = calculateFrom(s, idEnd+1)
        		case s[idEnd] == '-' || s[idEnd] == '+':
        			result, currNum = result+currNum*sign, 0
        			sign = 44 - int(s[idEnd]) // '-'=45; '+'=43
        		}
        	}
        
        	return result + currNum*sign, idEnd
        }
        

        4.7.1042 - 2023-11-04 10:36:18 +0300 MSK

        Last Moment Before All Ants Fall Out of a Plank

        Code

        
        func getLastMoment(n int, left []int, right []int) int {
            return max(slices.Max(append(left, 0)), n - slices.Min(append(right, n)))
        }
        

        4.7.1043 - 2023-11-04 10:30:12 +0300 MSK

        Last Moment Before All Ants Fall Out of a Plank

        Code

        func getLastMoment(n int, left []int, right []int) int {
            maxLeft := 0
            for _, val := range left {
                if val > maxLeft {
                    maxLeft = val
                }
            }
            minRight := n
            for _, val := range right {
                if val < minRight {
                    minRight = val
                }
            }
            return max(maxLeft, n - minRight)
        }
        

        4.7.1044 - 2023-11-04 10:29:26 +0300 MSK

        Last Moment Before All Ants Fall Out of a Plank

        Code

        func getLastMoment(n int, left []int, right []int) int {
            maxLeft := 0
            for _, val := range left {
                if val > maxLeft {
                    maxLeft = val
                }
            }
            
            minRight := n
            for _, val := range right {
                if val < minRight {
                    minRight = val
                }
            }
            return max(maxLeft, n - minRight)
        }
        

        4.7.1045 - 2023-11-03 15:20:27 +0300 MSK

        Kth Smallest Element in a BST

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func kthSmallest(root *TreeNode, k int) int {
            heap := binaryheap.NewWithIntComparator()
            queue := []*TreeNode{root}
        
            for length := len(queue); length > 0; length = len(queue) {
                for i := 0; i < length; i++ {
                    node := queue[i]
                    if node == nil {
                        continue
                    }
                    heap.Push(node.Val)
                    queue = append(queue, node.Left, node.Right)
                }
                queue = queue[length:]
            }
            var answer any
            for i := 0; i < k; i++ {
                answer, _ = heap.Pop()
            }
            return answer.(int)
        }
        

        4.7.1046 - 2023-11-03 12:40:06 +0300 MSK

        Flatten Binary Tree to Linked List

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func flatten(root *TreeNode)  {
            if root == nil {
                return
            }
            right := root.Right
            root.Right = nil
            list := &TreeNode{0, nil, nil}
            listTail := flattenNode(root, list)
            if right != nil {
                flattenNode(right, listTail)
            }
        }
        
        func flattenNode(node, listTail *TreeNode) *TreeNode {
            left, right := node.Left, node.Right
            node.Left, node.Right = nil, nil
            listTail.Right = node
            listTail = listTail.Right
            if left != nil {
                listTail = flattenNode(left, listTail)
            }
            if right != nil {
                listTail = flattenNode(right, listTail)
            }
            return listTail
        }
        

        4.7.1047 - 2023-11-03 12:14:46 +0300 MSK

        Build an Array With Stack Operations

        Code

        func buildArray(target []int, n int) []string {
            ops := []string{}
            length := len(target)
            matchNext, matchNextVal := 0, target[0]
            for i := 1; i <= n; i++ {
                if i == matchNextVal {
                    ops = append(ops, "Push")
                    matchNext += 1
                    if matchNext == length {
                        break
                    }
                    matchNextVal = target[matchNext]
                } else {
                    ops = append(ops, "Push", "Pop")
                }
            }
            return ops
        }
        

        4.7.1048 - 2023-11-03 12:13:05 +0300 MSK

        Build an Array With Stack Operations

        Code

        func buildArray(target []int, n int) []string {
            ops := []string{}
            length := len(target)
            matchNext := 0
            for i := 1; i <= n; i++ {
                if matchNext == length {
                    break
                }
                ops = append(ops, "Push")
                if i == target[matchNext] {
                    matchNext += 1
                } else {
                    ops = append(ops, "Pop")
                }
            }
            return ops
        }
        

        4.7.1049 - 2023-11-02 14:33:34 +0300 MSK

        Sort List

        Code

        
        func sortList(head *ListNode) *ListNode {
        	if head == nil || head.Next == nil {
        		return head
        	}
        	if head.Next.Next == nil {
        		a := head
        		b := head.Next
        		if a.Val <= b.Val {
        			a.Next = b
        			b.Next = nil
        			return a
        		} else {
        			b.Next = a
        			a.Next = nil
        			return b
        		}
        	}
        	slow := head
        	fast := head
        	for fast != nil && fast.Next != nil {
        		slow = slow.Next
        		fast = fast.Next.Next
        	}
        	nextList := slow.Next
        	slow.Next = nil
        	list1 := sortList(head)
        	list2 := sortList(nextList)
        	dummy := &ListNode{Val: -1, Next: nil}
        	it := dummy
        	for list1 != nil && list2 != nil {
        		if list1.Val <= list2.Val {
        			it.Next = list1
        			list1 = list1.Next
        		} else {
        			it.Next = list2
        			list2 = list2.Next
        		}
        		it = it.Next
        	}
        	if list1 != nil {
        		it.Next = list1
        	} else {
        		it.Next = list2
        	}
        	return dummy.Next
        }
        

        4.7.1050 - 2023-11-02 13:32:46 +0300 MSK

        Count Nodes Equal to Average of Subtree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func averageOfSubtree(root *TreeNode) int {
            _, _, answer := getAverage(root)
            return answer
        }
        
        func getAverage(root *TreeNode) (int, int, int) {
            if root == nil {
                return 0, 0, 0
            }
            sum, count, validNodes := root.Val, 1, 0
            leftSum, leftCount, leftValidNodes := getAverage(root.Left)
            rightSum, rightCount, rightValidNodes := getAverage(root.Right)
            validNodes += leftValidNodes + rightValidNodes
            sum += leftSum + rightSum
            count += leftCount + rightCount
            if sum / count == root.Val {
                validNodes += 1
            }
            return sum, count, validNodes
        }
        

        4.7.1051 - 2023-11-01 15:59:19 +0300 MSK

        Sum Root to Leaf Numbers

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        
        type queueItem struct {
            node *TreeNode
            sum int
        }
        func sumNumbers(root *TreeNode) int {
            if root == nil {
                return 0
            }
            queue := []queueItem{queueItem{root, 0}}
            sum := 0
            for length := len(queue); length > 0; length = len(queue) {
                for i := 0; i < length; i++ {
                    item := queue[i]
                    if item.node == nil {
                        continue
                    }
                    left, right, newVal := item.node.Left, item.node.Right, item.node.Val + item.sum * 10
                    if left == nil && right == nil {
                        sum += newVal
                    } else {
                        queue = append(queue, queueItem{left, newVal}, queueItem{right, newVal})
                    }
                }
                queue = queue[length:]
            }
            return sum
        }
        

        4.7.1052 - 2023-11-01 15:51:19 +0300 MSK

        Sum Root to Leaf Numbers

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func sumNumbers(root *TreeNode) int {
            return getSum(root, 0)
        }
        
        func getSum(root *TreeNode, parentVal int) int {
            if root == nil {
                return 0
            }
            newVal := root.Val + parentVal * 10
            if root.Left == nil && root.Right == nil {
                return newVal
            }
            return getSum(root.Left, newVal) + getSum(root.Right, newVal)
        }
        

        4.7.1053 - 2023-11-01 15:01:54 +0300 MSK

        Lowest Common Ancestor of a Binary Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
         func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
            if root == nil {
        		return nil
        	}
            if root == p || root == q {
        		return root
        	}
            left, right := lowestCommonAncestor(root.Left, p, q), lowestCommonAncestor(root.Right, p, q)
            if left != nil && right != nil {
        		return root
        	}
        	if left != nil {
        		return left
        	}
        	return right
        }
        

        4.7.1054 - 2023-11-01 15:00:05 +0300 MSK

        Lowest Common Ancestor of a Binary Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        
        func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
            isAncestorMap := map[int][2]bool{}
            dfs(root, p, q, isAncestorMap)
            isAncestor := func (node *TreeNode) bool {
                if node == nil {
                    return false
                }
                hasNodes := isAncestorMap[node.Val]
                return hasNodes[0] && hasNodes[1]
            }
        
            for {
                left, right := root.Left, root.Right
                if isAncestor(left) {
                    root = left
                } else if isAncestor(right) {
                    root = right
                } else {
                    break
                }
            }
            return root
        }
        
        func dfs(root, p, q *TreeNode, isAncestorMap map[int][2]bool) (bool, bool)  {
            if root == nil {
                return false, false
            }
            hasPLeft, hasQLeft := dfs(root.Left, p, q, isAncestorMap)
            hasPRight, hasQRight := dfs(root.Right, p, q, isAncestorMap)
            hasP, hasQ := hasPLeft || hasPRight, hasQLeft || hasQRight
            if root == p {
                hasP = true
            }
            if root == q {
                hasQ = true
            }
            isAncestorMap[root.Val] = [2]bool{hasP, hasQ}
            return hasP, hasQ
        }
        

        4.7.1055 - 2023-11-01 12:34:06 +0300 MSK

        Find Mode in Binary Search Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func findMode(root *TreeNode) []int {
            if root == nil {
                return []int{}
            }
            counter := map[int]int{}
            queue := []*TreeNode{root}
            for length := len(queue); length > 0; length = len(queue) {
                for i := 0; i < length; i++ {
                    node := queue[i]
                    if node == nil {
                        continue
                    }
                    left, right, val := node.Left, node.Right, node.Val
                    if _, ok := counter[val]; ok {
                        counter[val] +=  1
                    } else {
                        counter[val] = 1
                    }
                    queue = append(queue, left, right)
                }
                queue = queue[length:]
            }
            maxCount, answer := 0, []int{}
            for key, count := range counter {
                if count < maxCount {
                    continue
                }
                if count > maxCount {
                    answer = answer[:0]
                    maxCount = count
                }
                answer = append(answer, key)
            }
            return answer
        }
        

        4.7.1056 - 2023-11-01 12:32:26 +0300 MSK

        Find Mode in Binary Search Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func findMode(root *TreeNode) []int {
            if root == nil {
                return []int{}
            }
            counter := map[int]int{}
            queue := []*TreeNode{root}
            for length := len(queue); length > 0; length = len(queue) {
                for i := 0; i < length; i++ {
                    node := queue[i]
                    if node == nil {
                        continue
                    }
                    if val, ok := counter[node.Val]; ok {
                        counter[node.Val] = val + 1
                    } else {
                        counter[node.Val] = 1
                    }
                    queue = append(queue, node.Left, node.Right)
                }
                queue = queue[length:]
            }
            maxCount, answer := 0, []int{}
            for key, count := range counter {
                if count < maxCount {
                    continue
                }
                if count > maxCount {
                    answer = answer[:0]
                    maxCount = count
                }
                answer = append(answer, key)
            }
            return answer
        }
        

        4.7.1057 - 2023-11-01 12:28:17 +0300 MSK

        Find Mode in Binary Search Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func findMode(root *TreeNode) []int {
            if root == nil {
                return []int{}
            }
            counter := map[int]int{}
            dfs(root, counter)
            maxCount, answer := 0, []int{}
            for key, count := range counter {
                if count < maxCount {
                    continue
                }
                if count > maxCount {
                    answer = answer[:0]
                    maxCount = count
                }
                answer = append(answer, key)
            }
            return answer
        }
        
        func dfs(root *TreeNode, counter map[int]int) {
            if root == nil {
                return
            }
            if _, ok := counter[root.Val]; ok {
                counter[root.Val] += 1
            } else {
                counter[root.Val] = 1
            }
            dfs(root.Left, counter)
            dfs(root.Right, counter)
        }
        

        4.7.1058 - 2023-11-01 12:20:58 +0300 MSK

        Find Mode in Binary Search Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func findMode(root *TreeNode) []int {
            if root == nil {
                return []int{}
            }
            counter := map[int]int{}
            queue := []*TreeNode{root}
            for length := len(queue); length > 0; length = len(queue) {
                for i := 0; i < length; i++ {
                    node := queue[i]
                    if _, ok := counter[node.Val]; ok {
                        counter[node.Val] += 1
                    } else {
                        counter[node.Val] = 1
                    }
                    if node.Left != nil {
                        queue = append(queue, node.Left)
                    }
                    if node.Right != nil {
                        queue = append(queue, node.Right)
                    }
                }
                queue = queue[length:]
            }
            maxCount, answer := 0, []int{}
            for key, count := range counter {
                if count < maxCount {
                    continue
                }
                if count > maxCount {
                    answer = answer[:0]
                    maxCount = count
                }
                answer = append(answer, key)
            }
            return answer
        }
        

        4.7.1059 - 2023-10-31 19:12:05 +0300 MSK

        Validate Binary Search Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        type queueItem struct  {
            node *TreeNode
            max *int
            min *int
        }
        
        func isValidBST(root *TreeNode) bool {
            queue := []queueItem{queueItem{root, nil, nil}}
            for length := len(queue); length > 0; length = len(queue) {
                for i := 0; i < length; i++ {
                    item := queue[i]
                    if item.node == nil {
                        continue
                    }
                    node := item.node
                    if (item.max != nil && node.Val >= *item.max) || (item.min != nil && node.Val <= *item.min) {
                        return false
                    }
                    queue = append(
                        queue, 
                        queueItem{node.Left, &node.Val, item.min}, 
                        queueItem{node.Right, item.max, &node.Val},
                    )
                }
                queue = queue[length:]
            }
            return true
        }
        

        4.7.1060 - 2023-10-31 19:11:41 +0300 MSK

        Validate Binary Search Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        type queueItem struct  {
            node *TreeNode
            max *int
            min *int
        }
        
        func isValidBST(root *TreeNode) bool {
            queue := []queueItem{queueItem{root, nil, nil}}
            for length := len(queue); length > 0; length = len(queue) {
                for i := 0; i < length; i++ {
                    item := queue[i]
                    if item.node == nil {
                        continue
                    }
                    node := item.node
                    if (item.max != nil && node.Val >= *item.max) || (item.min != nil && node.Val <= *item.min) {
                        return false
                    }
                    queue = append(
                        queue, 
                        queueItem{node.Left, &node.Val, item.min}, 
                        queueItem{node.Right, item.max, &node.Val},
                    )
                }
                queue = queue[length:]
            }
            return true
        }
        

        4.7.1061 - 2023-10-31 18:59:17 +0300 MSK

        Validate Binary Search Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func isValidBST(root *TreeNode) bool {
            if root == nil {
                return false
            }
            return dfs(root.Left, &root.Val, nil) && dfs(root.Right, nil, &root.Val)
        }
        
        func dfs(root *TreeNode, max *int, min *int) bool {
            if root == nil {
                return true
            }
            if (max != nil && root.Val >= *max) || (min != nil && root.Val <= *min) {
                return false
            }
            return dfs(root.Left, &root.Val, min) && dfs(root.Right, max, &root.Val)
        }
        

        4.7.1062 - 2023-10-31 18:18:34 +0300 MSK

        Maximum Sum Circular Subarray

        Code

        func max(a, b int) int {
            if a > b {
                return a
            }
            return b
        }
        
        func min(a, b int) int {
            if a < b {
                return a
            }
            return b
        }
        
        func maxSubarraySumCircular(nums []int) int {
            var (
                max_sum_ending_here = 0
                min_sum_ending_here = 0
                max_sum_so_far = math.MinInt
                min_sum_so_far = math.MaxInt
                total = 0
            )
            for i := 0; i < len(nums); i++ {
                num := nums[i]
                total += num
                max_sum_ending_here += num
                min_sum_ending_here += num
                max_sum_so_far = max(max_sum_so_far, max_sum_ending_here)
                min_sum_so_far = min(min_sum_so_far, min_sum_ending_here)
                max_sum_ending_here = max(max_sum_ending_here, 0)
                min_sum_ending_here = min(min_sum_ending_here, 0)
            }
            if max_sum_so_far < 0 {
                return max_sum_so_far
            }
            return max(max_sum_so_far, total - min_sum_so_far)
        }
        

        4.7.1063 - 2023-10-31 18:15:28 +0300 MSK

        Maximum Sum Circular Subarray

        Code

        func max(a, b int) int {
            if a > b {
                return a
            }
            return b
        }
        
        func min(a, b int) int {
            if a < b {
                return a
            }
            return b
        }
        
        func maxSubarraySumCircular(nums []int) int {
            var (
                max_sum_ending_here = 0
                min_sum_ending_here = 0
                max_sum_so_far = math.MinInt
                min_sum_so_far = math.MaxInt
                total = 0
            )
            for i := 0; i < len(nums); i++ {
                total += nums[i]
                max_sum_ending_here += nums[i]
                min_sum_ending_here += nums[i]
                max_sum_so_far = max(max_sum_so_far, max_sum_ending_here)
                min_sum_so_far = min(min_sum_so_far, min_sum_ending_here)
                max_sum_ending_here = max(max_sum_ending_here, 0)
                min_sum_ending_here = min(min_sum_ending_here, 0)
            }
            if max_sum_so_far < 0 {
                return max_sum_so_far
            }
            return max(max_sum_so_far, total - min_sum_so_far)
        }
        

        4.7.1064 - 2023-10-31 18:13:57 +0300 MSK

        Maximum Sum Circular Subarray

        Code

        func max(a, b int) int {
            if a > b {
                return a
            }
            return b
        }
        
        func min(a, b int) int {
            if a < b {
                return a
            }
            return b
        }
        
        func maxSubarraySumCircular(nums []int) int {
            var max_sum_ending_here int = 0
            var min_sum_ending_here int = 0
            var max_sum_so_far int = math.MinInt
            var min_sum_so_far int = math.MaxInt
            var total = 0
            for i := 0; i < len(nums); i++ {
                total += nums[i]
                max_sum_ending_here += nums[i]
                min_sum_ending_here += nums[i]
                max_sum_so_far = max(max_sum_so_far, max_sum_ending_here)
                min_sum_so_far = min(min_sum_so_far, min_sum_ending_here)
                max_sum_ending_here = max(max_sum_ending_here, 0)
                min_sum_ending_here = min(min_sum_ending_here, 0)
            }
            if max_sum_so_far < 0 {
                return max_sum_so_far
            }
            return max(max_sum_so_far, total - min_sum_so_far)
        }
        

        4.7.1065 - 2023-10-31 11:33:38 +0300 MSK

        Find The Original Array of Prefix Xor

        Code

        func findArray(pref []int) []int {
            prev := pref[0]
            for i := 1; i < len(pref); i++ {
                cur := pref[i]
                prev, pref[i] = cur, prev ^ cur 
            }
            return pref
        }
        

        4.7.1066 - 2023-10-31 11:32:41 +0300 MSK

        Find The Original Array of Prefix Xor

        Code

        func findArray(pref []int) []int {
            prev := pref[0]
            for i := 1; i < len(pref); i++ {
                prev, pref[i] = pref[i], prev ^ pref[i] 
            }
            return pref
        }
        

        4.7.1067 - 2023-10-30 16:28:30 +0300 MSK

        Trapping Rain Water

        Code

        func trap(height []int) int {
            left, right := 0, len(height) - 1
            res := 0
            leftMax, rightMax := 0, 0
        
            for left < right {
                if height[left] < height[right] {
                    if height[left] >= leftMax {
                        leftMax = height[left]
                    } else {
                        res += (leftMax-height[left])
                    }
                    left++
                } else {
                    if height[right] >= rightMax {
                        rightMax = height[right]
                    } else {
                        res += (rightMax-height[right])
                    }
                    right--
                }
            }
        
            return res
        }
        

        4.7.1068 - 2023-10-30 16:16:38 +0300 MSK

        Find First and Last Position of Element in Sorted Array

        Code

        class Solution:
            def searchRange(self, nums: List[int], target: int) -> List[int]:
                def binary_search(nums, target, left):
                    low, high = 0, len(nums) - 1
                    index = -1
                    while low <= high:
                        mid = (low + high) // 2
                        if nums[mid] == target:
                            index = mid
                            if left:
                                high = mid - 1
                            else:
                                low = mid + 1
                        elif nums[mid] < target:
                            low = mid + 1
                        else:
                            high = mid - 1
                    return index
        
                left_index = binary_search(nums, target, left=True)
                right_index = binary_search(nums, target, left=False)
        
                return [left_index, right_index]
        

        4.7.1069 - 2023-10-30 16:03:18 +0300 MSK

        Minimum Genetic Mutation

        Code

        func minMutation(startGene string, endGene string, bank []string) int {
            if startGene == endGene {
                return 0
            }
        
            bank = append(bank, startGene)
        
            isMut := func (gene1 string, gene2 string) bool {
                foundDiff := false
                for i := 0; i < len(gene1); i++ {
                    if gene1[i] == gene2[i] {
                        continue
                    }
                    if foundDiff {
                        return false
                    }
                    foundDiff = true
                } 
                return foundDiff
            }
        
            graph := map[string][]string{}
        
            for i, gene1 := range bank {
                for _, gene2 := range bank[i+1:] {
                    if !isMut(gene1, gene2) {
                        continue
                    }
                    if _, ok := graph[gene1]; !ok {
                        graph[gene1] = []string{}
                    }
                    if _, ok := graph[gene2]; !ok {
                        graph[gene2] = []string{}
                    }
                    graph[gene1] = append(graph[gene1], gene2)
                    graph[gene2] = append(graph[gene2], gene1)
                }
            }
        
            queue, ok := graph[endGene]
            if !ok {
                return -1
            }
            delete(graph, endGene)
            num := 1
            for length := len(queue); length > 0; length = len(queue) {
                for i := 0; i < length; i++ {
                    gene := queue[i]
                    muts, ok := graph[gene]
                    if !ok {
                        continue
                    }
                    if gene == startGene {
                        return num 
                    }
                    delete(graph, gene)
                    queue = append(queue, muts...)
                }
                num += 1
                queue = queue[length:]
            }
        
            return -1
        }
        

        4.7.1070 - 2023-10-30 15:58:41 +0300 MSK

        Minimum Genetic Mutation

        Code

        func minMutation(startGene string, endGene string, bank []string) int {
            if startGene == endGene {
                return 0
            }
        
            bank = append(bank, startGene)
        
            isMut := func (gene1 string, gene2 string) bool {
                foundDiff := false
                for i := 0; i < len(gene1); i++ {
                    if gene1[i] == gene2[i] {
                        continue
                    }
                    if foundDiff {
                        return false
                    }
                    foundDiff = true
                } 
                return foundDiff
            }
        
            graph := map[string][]string{}
        
            for i, gene1 := range bank {
                for _, gene2 := range bank[i+1:] {
                    if !isMut(gene1, gene2) {
                        continue
                    }
                    if _, ok := graph[gene1]; !ok {
                        graph[gene1] = []string{}
                    }
                    if _, ok := graph[gene2]; !ok {
                        graph[gene2] = []string{}
                    }
                    graph[gene1] = append(graph[gene1], gene2)
                    graph[gene2] = append(graph[gene2], gene1)
                }
            }
        
            queue, ok := graph[endGene]
            if !ok {
                return -1
            }
            visited := map[string]struct{}{endGene: struct{}{}}
            num := 1
            for length := len(queue); length > 0; length = len(queue) {
                for i := 0; i < length; i++ {
                    gene := queue[i]
                    if _, ok := visited[gene]; ok {
                        continue
                    }
                    if gene == startGene {
                        return num 
                    }
                    visited[gene] = struct{}{}
                    queue = append(queue, graph[gene]...)
                }
                num += 1
                queue = queue[length:]
            }
        
            return -1
        }
        

        4.7.1071 - 2023-10-30 14:32:47 +0300 MSK

        Binary Tree Zigzag Level Order Traversal

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func zigzagLevelOrder(root *TreeNode) [][]int {
            if root == nil {
                return [][]int{}
            }
        
            queue, answer := []*TreeNode{root}, [][]int{}
            ltr := true
        
            for length := len(queue); length != 0; length = len(queue) {
                answerRow := []int{}
                for i := 0; i < length; i++ {
                    node := queue[i]
                    if node.Left != nil {
                        queue = append(queue, node.Left)
                    }
                    if node.Right != nil {
                        queue = append(queue, node.Right)
                    }
                    answerRow = append(answerRow, node.Val)
                }
                if !ltr {
                    slices.Reverse(answerRow)
                }
                queue = queue[length:]
                ltr = !ltr
                answer = append(answer, answerRow)
            }
        
            return answer
        }
        

        4.7.1072 - 2023-10-30 14:31:36 +0300 MSK

        Binary Tree Zigzag Level Order Traversal

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func zigzagLevelOrder(root *TreeNode) [][]int {
            if root == nil {
                return [][]int{}
            }
        
            queue, answer := []*TreeNode{root}, [][]int{}
            ltr := true
        
            for length := len(queue); length != 0; length = len(queue) {
                answerRow := []int{}
                for i := 0; i < length; i++ {
                    node := queue[i]
                    if node.Left != nil {
                        queue = append(queue, node.Left)
                    }
                    if node.Right != nil {
                        queue = append(queue, node.Right)
                    }
                    if ltr {
                        answerRow = append(answerRow, node.Val)
                    } else {
                        answerRow = append([]int{node.Val}, answerRow...)
                    }
                }
                queue = queue[length:]
                ltr = !ltr
                answer = append(answer, answerRow)
            }
        
            return answer
        }
        

        4.7.1073 - 2023-10-30 14:14:48 +0300 MSK

        Binary Tree Zigzag Level Order Traversal

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func zigzagLevelOrder(root *TreeNode) [][]int {
            if root == nil {
                return [][]int{}
            }
        
            queue, answer := []*TreeNode{root}, [][]int{}
            leftToRight := true
        
            for length := len(queue); length != 0; length = len(queue) {
                answerRow := []int{}
        
                for i := 0; i < length; i++ {
                    node := queue[0]
                    queue = queue[1:]
        
                    answerRow = append(answerRow, node.Val)
                    if left := node.Left; left != nil {
                        queue = append(queue, left)
                    }
                    if right := node.Right; right != nil {
                        queue = append(queue, right)
                    }
                }
                if !leftToRight {
                    slices.Reverse(answerRow)
                }
                leftToRight = !leftToRight
                answer = append(answer, answerRow)
            }
        
            return answer
        }
        

        4.7.1074 - 2023-10-30 13:59:23 +0300 MSK

        Binary Tree Level Order Traversal

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func levelOrder(root *TreeNode) [][]int {
            queue, answer := []*TreeNode{root}, [][]int{}
        
            for length := len(queue); length != 0; length = len(queue) {
                answerRow := []int{}
                for i := 0; i < length; i++ {
                    node := queue[0]
                    queue = queue[1:]
                    if node == nil {
                        continue
                    }
                    answerRow = append(answerRow, node.Val)
                    queue = append(queue, node.Left, node.Right)
                }
                if len(answerRow) != 0 {
                    answer = append(answer, answerRow)
                }
            }
        
            return answer
        }
        

        4.7.1075 - 2023-10-30 13:51:15 +0300 MSK

        Binary Tree Level Order Traversal

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func levelOrder(root *TreeNode) [][]int {
            if root == nil {
                return [][]int{}
            }
        
            stack, answer := []*TreeNode{root}, [][]int{}
        
            for length := len(stack); length != 0; length = len(stack) {
                answerRow := []int{}
                for i := 0; i < length; i++ {
                    node := stack[0]
                    answerRow = append(answerRow, node.Val)
                    stack = stack[1:]
                    if left := node.Left; left != nil {
                        stack = append(stack, node.Left)
                    }
                    if right := node.Right; right != nil {
                        stack = append(stack, node.Right)
                    }
                }
                answer = append(answer, answerRow)
            }
        
            return answer
        }
        

        4.7.1076 - 2023-10-30 13:39:35 +0300 MSK

        Binary Tree Right Side View

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func rightSideView(root *TreeNode) []int {
            if root == nil {
                return []int{}
            }
        
            queue, answer := []*TreeNode{root}, []int{}
        
            for length := len(queue); length != 0; length = len(queue) {
                for i := 0; i < length; i++ {
                    node := queue[0]
                    queue = queue[1:]
                    if i == length - 1 {
                        answer = append(answer, node.Val)
                    }
                    if left := node.Left; left != nil {
                        queue = append(queue, left)
                    }
                    if right := node.Right; right != nil {
                        queue = append(queue, right)
                    }
                }
            }
        
            return answer
        } 
        

        4.7.1077 - 2023-10-30 13:33:19 +0300 MSK

        Average of Levels in Binary Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func averageOfLevels(root *TreeNode) []float64 {
            if root == nil {
                return []float64{}
            }
            queue, answer := []*TreeNode{root}, []float64{}
        
            for length := len(queue); length != 0; length = len(queue) {
                av := 0
                for i := 0; i < length; i++ {
                    node := queue[0]
                    queue = queue[1:]
                    av += node.Val
                    if left := node.Left; left != nil {
                        queue = append(queue, left)
                    }
                    if right := node.Right; right != nil {
                        queue = append(queue, right)
                    }
                }
                answer = append(answer, float64(av) / float64(length))
            }
        
            return answer
        }
        

        4.7.1078 - 2023-10-30 13:26:37 +0300 MSK

        Average of Levels in Binary Tree

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func averageOfLevels(root *TreeNode) []float64 {
            if root == nil {
                return []float64{}
            }
            qCur, qNext, answer := []*TreeNode{root}, []*TreeNode{}, []float64{}
        
            for len(qCur) != 0 {
                av := 0
                for _, node := range qCur {
                    av += node.Val
                    if left := node.Left; left != nil {
                        qNext = append(qNext, left)
                    }
                    if right := node.Right; right != nil {
                        qNext = append(qNext, right)
                    }
                }
                answer = append(answer, float64(av) / float64(len(qCur)))
                qCur = qCur[:0]
                qCur, qNext = qNext, qCur
            }
        
            return answer
        }
        

        4.7.1079 - 2023-10-30 13:17:08 +0300 MSK

        Binary Tree Right Side View

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func rightSideView(root *TreeNode) []int {
            if root == nil {
                return []int{}
            }
        
            q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}
        
            for len(q_cur) != 0 {
                for _, node := range q_cur {
                    if left := node.Left; left != nil {
                        q_next = append(q_next, left)
                    }
                    if right := node.Right; right != nil {
                        q_next = append(q_next, right)
                    }
                }
        
                answer = append(answer, q_cur[len(q_cur) - 1].Val)
                q_cur = q_cur[:0]
                q_cur, q_next = q_next, q_cur
            }
        
            return answer
        } 
        

        4.7.1080 - 2023-10-30 13:16:47 +0300 MSK

        Binary Tree Right Side View

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func rightSideView(root *TreeNode) []int {
            if root == nil {
                return []int{}
            }
        
            q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}
        
            for len(q_cur) != 0 {
                var last int
                for _, node := range q_cur {
                    if left := node.Left; left != nil {
                        q_next = append(q_next, left)
                    }
                    if right := node.Right; right != nil {
                        q_next = append(q_next, right)
                    }
                    last = node.Val
                }
        
                answer = append(answer, last)
                q_cur = q_cur[:0]
                q_cur, q_next = q_next, q_cur
            }
        
            return answer
        } 
        

        4.7.1081 - 2023-10-30 13:16:38 +0300 MSK

        Binary Tree Right Side View

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func rightSideView(root *TreeNode) []int {
            if root == nil {
                return []int{}
            }
        
            q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}
        
            for len(q_cur) != 0 {
                var last int
                for _, node := range q_cur {
                    if left := node.Left; left != nil {
                        q_next = append(q_next, left)
                    }
                    if right := node.Right; right != nil {
                        q_next = append(q_next, right)
                    }
                    last = node.Val
                }
        
                answer = append(answer, last)
                q_cur = q_cur[:0]
                q_cur, q_next = q_next, q_cur
            }
        
            return answer
        } 
        

        4.7.1082 - 2023-10-30 13:13:00 +0300 MSK

        Binary Tree Right Side View

        Code

        /**
         * Definition for a binary tree node.
         * type TreeNode struct {
         *     Val int
         *     Left *TreeNode
         *     Right *TreeNode
         * }
         */
        func rightSideView(root *TreeNode) []int {
            if root == nil {
                return []int{}
            }
        
            q_cur, q_next, answer := []*TreeNode{root}, []*TreeNode{}, []int{}
        
            for length := len(q_cur); length > 0; length = len(q_cur) {
                for _, node := range q_cur {
                    if left := node.Left; left != nil {
                        q_next = append(q_next, left)
                    }
                    if right := node.Right; right != nil {
                        q_next = append(q_next, right)
                    }
                }
        
                answer = append(answer, q_cur[length - 1].Val)
                q_cur = q_cur[:0]
                q_cur, q_next = q_next, q_cur
            }
        
            return answer
        } 
        

        4.7.1083 - 2023-10-30 12:17:05 +0300 MSK

        Binary Tree Right Side View

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
                if not root:
                    return []
                
                q_cur, q_next, answer = deque(), deque(), []
                q_cur.append(root)
        
                while q_cur:
                    last_val = None
                    
                    while q_cur:
                        node = q_cur.popleft()
                        last_val = node.val
                        if node.left:
                            q_next.append(node.left)
                        if node.right:
                            q_next.append(node.right)
                    
                    q_cur, q_next = q_next, q_cur
                    answer.append(last_val)
            
                return answer
        

        4.7.1084 - 2023-10-30 12:10:35 +0300 MSK

        Binary Tree Right Side View

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
                if not root:
                    return []
                cur, nxt = [root], []
                answer = []
                
                while cur:
                    last_node = cur.pop()
                    if last_node.right:
                        nxt.append(last_node.right)
                    if last_node.left:
                        nxt.append(last_node.left)
                    answer.append(last_node.val)
                    
                    while cur:
                        node = cur.pop()
                        if node.right:
                            nxt.append(node.right)
                        if node.left:
                            nxt.append(node.left)
                    
                    cur.clear()
                    nxt.reverse()
                    cur, nxt = nxt, cur
        
                return answer
        

        4.7.1085 - 2023-10-30 10:51:12 +0300 MSK

        Sort Integers by The Number of 1 Bits

        Code

        class Solution:
            def sortByBits(self, arr: List[int]) -> List[int]:
                return tuple(num for num in sorted(arr, key=lambda num: (num.bit_count(), num)))
        

        4.7.1086 - 2023-10-29 19:36:33 +0300 MSK

        Poor Pigs

        Code

        class Solution:
            def poorPigs(self, buckets: int, a: int, b: int) -> int:
                pigs = 0
                while (b / a + 1) ** pigs < buckets:
                    pigs += 1
        
                return pigs 
        

        4.7.1087 - 2023-10-28 17:51:04 +0300 MSK

        Count Vowels Permutation

        Code

        class Solution:
            def countVowelPermutation(self, n: int) -> int:
                MOD = 10**9 + 7
                
                a, e, i, o, u = 1, 1, 1, 1, 1
                
                for _ in range(1, n):
                    a_next = e
                    e_next = (a + i) % MOD
                    i_next = (a + e + o + u) % MOD
                    o_next = (i + u) % MOD
                    u_next = a
                    
                    a, e, i, o, u = a_next, e_next, i_next, o_next, u_next
                
                return (a + e + i + o + u) % MOD
        

        4.7.1088 - 2023-10-27 17:47:50 +0300 MSK

        Longest Palindromic Substring

        Code

        class Solution:
            def longestPalindrome(self, s: str) -> str:
                n = len(s)
                dp = [[False] * n for _ in range(n)]
                ans = [0, 0]
                
                for i in range(n):
                    dp[i][i] = True
                
                for i in range(n - 1):
                    if s[i] == s[i + 1]:
                        dp[i][i + 1] = True
                        ans = [i, i + 1]
        
                for diff in range(2, n):
                    for i in range(n - diff):
                        j = i + diff
                        if s[i] == s[j] and dp[i + 1][j - 1]:
                            dp[i][j] = True
                            ans = [i, j]
        
                i, j = ans
                return s[i:j + 1]
        

        4.7.1089 - 2023-10-26 23:07:22 +0300 MSK

        Binary Trees With Factors

        Code

        MOD = 10**9 + 7
        
        class Solution:
            def numFactoredBinaryTrees(self, arr: List[int]) -> int:
                arr.sort()
                s = set(arr)
                dp = {x: 1 for x in arr}
                
                for i in arr:
                    for j in arr:
                        if j > i**0.5:
                            break
                        if i % j == 0 and i // j in s:
                            if i // j == j:
                                dp[i] += dp[j] * dp[j]
                            else:
                                dp[i] += dp[j] * dp[i // j] * 2
                            dp[i] %= MOD
                
                return sum(dp.values()) % MOD
        

        4.7.1090 - 2023-10-25 13:37:39 +0300 MSK

        Design Add and Search Words Data Structure

        Code

        class TrieNode:
            def __init__(self):
                self.children = {}
                self.is_word = False
        
        class WordDictionary:
        
            def __init__(self):
                self.root = TrieNode()
        
            def addWord(self, word: str) -> None:
                cur = self.root
                for char in word:
                    cur = cur.children.setdefault(char, TrieNode())
                cur.is_word = True
        
            def search(self, word: str) -> bool:
                cur, nxt = [self.root], []
                
                for char in word:
                    if not cur:
                        return False
        
                    if char == ".":
                        for node in cur:
                            nxt.extend(node.children.values())
                    else:
                        for node in cur:
                            if char in node.children:
                                nxt.append(node.children[char]) 
                        
                    cur.clear()
                    cur, nxt = nxt, cur
        
                return any(node.is_word for node in cur)
                    
        
        
        
        # Your WordDictionary object will be instantiated and called as such:
        # obj = WordDictionary()
        # obj.addWord(word)
        # param_2 = obj.search(word)
        

        4.7.1091 - 2023-10-25 11:31:06 +0300 MSK

        K-th Symbol in Grammar

        Code

        class Solution:
            def kthGrammar(self, n: int, k: int) -> int:
        
                def get(row: int, column: int) -> int:
                    if column == 0 or column == 1:
                        return column
                    
                    prev_row_length = 2 ** (row - 1)
                    if column >= prev_row_length:
                        return 1 ^ get(row - 1, column - prev_row_length)
                    return get(row - 1, column)
        
                return get(n - 1, k - 1)
        
                # 0
                # 0 1
                # 0 1 1 0
                # 0 1 1 0 1 0 0 1
                # 0 1 1 0 1 0 0 1
        

        4.7.1092 - 2023-10-24 14:55:16 +0300 MSK

        Find Largest Value in Each Tree Row

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def largestValues(self, root: Optional[TreeNode]) -> List[int]:
                if not root:
                    return []
        
                largest = []
                cur, nxt = [root], []
                cur_val = None
                while cur or nxt:
                    while cur:
                        node = cur.pop()
                        if cur_val is None or node.val > cur_val:
                            cur_val = node.val
                        if node.left:
                            nxt.append(node.left)
                        if node.right:
                            nxt.append(node.right)
                    largest.append(cur_val)
                    cur.clear()
                    cur_val = None
                    cur, nxt = nxt, cur
                return largest
        

        4.7.1093 - 2023-10-23 12:26:07 +0300 MSK

        Power of Four

        Code

        class Solution:
            def isPowerOfFour(self, n: int) -> bool:
                # Check if the number is greater than zero and is a power of two
                if n > 0 and (n & (n - 1)) == 0:
                    # Check if the number is of the form 4^x
                    return n & 0x55555555 == n
                else:
                    return False
        

        4.7.1094 - 2023-10-22 13:57:47 +0300 MSK

        Maximum Score of a Good Subarray

        Code

        class Solution:
            def maximumScore(self, nums: List[int], k: int) -> int:
                n = len(nums)
                left = k
                right = k
                ans = nums[k]
                curr_min = nums[k]
                
                while left > 0 or right < n - 1:
                    if (nums[left - 1] if left else 0) < (nums[right + 1] if right < n - 1 else 0):
                        right += 1
                        curr_min = min(curr_min, nums[right])
                    else:
                        left -= 1
                        curr_min = min(curr_min, nums[left])
        
                    ans = max(ans, curr_min * (right - left + 1))
                
                return ans
        

        4.7.1095 - 2023-10-21 14:20:53 +0300 MSK

        Constrained Subsequence Sum

        Code

        import heapq
        
        class Solution:
            def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
                heap = [(-nums[0], 0)]
                ans = nums[0]
                
                for i in range(1, len(nums)):
                    while i - heap[0][1] > k:
                        heapq.heappop(heap)
        
                    curr = max(0, -heap[0][0]) + nums[i]
                    ans = max(ans, curr)
                    heapq.heappush(heap, (-curr, i))
        
                return ans
        

        4.7.1096 - 2023-10-20 16:11:39 +0300 MSK

        Flatten Nested List Iterator

        Code

        # """
        # This is the interface that allows for creating nested lists.
        # You should not implement it, or speculate about its implementation
        # """
        #class NestedInteger:
        #    def isInteger(self) -> bool:
        #        """
        #        @return True if this NestedInteger holds a single integer, rather than a nested list.
        #        """
        #
        #    def getInteger(self) -> int:
        #        """
        #        @return the single integer that this NestedInteger holds, if it holds a single integer
        #        Return None if this NestedInteger holds a nested list
        #        """
        #
        #    def getList(self) -> [NestedInteger]:
        #        """
        #        @return the nested list that this NestedInteger holds, if it holds a nested list
        #        Return None if this NestedInteger holds a single integer
        #        """
        
        class NestedIterator:
            def __init__(self, nestedList: [NestedInteger]):
                self.get_next = self.get_next_gen(nestedList)
                self.next_val = next(self.get_next, None)
        
            def get_next_gen(self, nestedList: List[NestedInteger]) -> Generator[None, None, int]:
                for ni in nestedList:
                    if ni.isInteger():
                        yield ni.getInteger()
                    else:
                        yield from self.get_next_gen(ni.getList())
        
            def next(self) -> int: 
                answer, self.next_val = self.next_val, next(self.get_next, None)
                return answer
            
            def hasNext(self) -> bool:
                return self.next_val is not None
        
        # Your NestedIterator object will be instantiated and called as such:
        # i, v = NestedIterator(nestedList), []
        # while i.hasNext(): v.append(i.next())
        

        4.7.1097 - 2023-10-20 16:06:36 +0300 MSK

        Flatten Nested List Iterator

        Code

        # """
        # This is the interface that allows for creating nested lists.
        # You should not implement it, or speculate about its implementation
        # """
        #class NestedInteger:
        #    def isInteger(self) -> bool:
        #        """
        #        @return True if this NestedInteger holds a single integer, rather than a nested list.
        #        """
        #
        #    def getInteger(self) -> int:
        #        """
        #        @return the single integer that this NestedInteger holds, if it holds a single integer
        #        Return None if this NestedInteger holds a nested list
        #        """
        #
        #    def getList(self) -> [NestedInteger]:
        #        """
        #        @return the nested list that this NestedInteger holds, if it holds a nested list
        #        Return None if this NestedInteger holds a single integer
        #        """
        
        class NestedIterator:
            def __init__(self, nestedList: [NestedInteger]):
                self.list = []
                self.flatten(self.list, nestedList)
                self.cur = 0
                self.length = len(self.list)
        
            def flatten(self, flatList: List[int], nestedList: List[NestedInteger]):
                for ni in nestedList:
                    if ni.isInteger():
                        flatList.append(ni.getInteger())
                    else:
                        self.flatten(flatList, ni.getList())
        
            def next(self) -> int: 
                answer = self.list[self.cur]
                self.cur += 1
                return answer
            
            def hasNext(self) -> bool:
                return self.cur < self.length
        
        # Your NestedIterator object will be instantiated and called as such:
        # i, v = NestedIterator(nestedList), []
        # while i.hasNext(): v.append(i.next())
        

        4.7.1098 - 2023-10-19 17:09:46 +0300 MSK

        Backspace String Compare

        Code

        class Solution:
            def backspaceCompare(self, s: str, t: str) -> bool:
                i1, i2 = len(s) - 1, len(t) - 1
                skip1, skip2 = 0, 0
        
                while i1 >= 0 or i2 >= 0:
                    char1, char2 = s[i1] if i1 >= 0 else "", t[i2] if i2 >= 0 else ""
                    if char1 == "#":
                        i1 -= 1
                        skip1 += 1
                    elif char2 == "#":
                        i2 -= 1
                        skip2 += 1
                    elif skip1 > 0:
                        i1 -= 1
                        skip1 -= 1
                    elif skip2 > 0:
                        i2 -= 1
                        skip2 -= 1
                    elif char1 != char2:
                        return False
                    else:
                        i1 -= 1
                        i2 -= 1
                
                return True 
        

        4.7.1099 - 2023-10-18 19:38:53 +0300 MSK

        Parallel Courses III

        Code

        class Solution:
            def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
                graph = defaultdict(list)
                indegree = [0] * n
                
                for (x, y) in relations:
                    graph[x - 1].append(y - 1)
                    indegree[y - 1] += 1
                
                queue = deque()
                max_time = [0] * n
                for node in range(n):
                    if indegree[node] == 0:
                        queue.append(node)
                        max_time[node] = time[node]
        
                while queue:
                    node = queue.popleft()
                    for neighbor in graph[node]:
                        max_time[neighbor] = max(max_time[neighbor], max_time[node] + time[neighbor])
                        indegree[neighbor] -= 1
                        if indegree[neighbor] == 0:
                            queue.append(neighbor)
        
                return max(max_time)
        

        4.7.1100 - 2023-10-17 18:45:21 +0300 MSK

        Validate Binary Tree Nodes

        Code

        class Solution:
            def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
                parents = [-1] * n
        
                for i in range(n):
                    left, right = leftChild[i], rightChild[i] 
                    left_valid, right_valid = left != -1, right != -1
                    if (left_valid and parents[left] != -1) or (
                        right_valid and parents[right] != -1
                    ):
                        return False
                    if left_valid:
                        parents[left] = i
                    if right_valid:
                        parents[right] = i
        
                    parent = parents[i]
                    if parent != -1 and (parent == left or parent == right):
                        return False
        
                root = None
                for i, node in enumerate(parents):
                    if node == -1 and root is not None:
                        return False
                    if node == -1:
                        root = i
        
                if root is None:
                    return False
        
                to_visit = [root]
                visited = set()
        
                while to_visit:
                    node = to_visit.pop()
                    if node in visited:
                        return False
                    visited.add(node)
                    left, right = leftChild[node], rightChild[node]
                    if left != -1:
                        to_visit.append(left)
                    if right != -1:
                        to_visit.append(right)
        
                return len(visited) == n 
                
        

        4.7.1101 - 2023-10-16 20:32:07 +0300 MSK

        Pascal’s Triangle II

        Code

        class Solution:
            def getRow(self, rowIndex: int) -> List[int]:
                cur, prev = [], [1]
                row = 0
        
                while row < rowIndex:
                    cur.append(1)
                    for i in range(1, len(prev)):
                        cur.append(prev[i] + prev[i-1])
                    cur.append(1)
                    prev.clear()
                    cur, prev = prev, cur
                    row += 1
                
                return prev 
        

        4.7.1102 - 2023-10-15 13:05:28 +0300 MSK

        Number of Ways to Stay in the Same Place After Some Steps

        Code

        class Solution:
            def numWays(self, steps: int, arrLen: int) -> int:
                @cache
                def dp(curr, remain):
                    if remain == 0:
                        if curr == 0:
                            return 1
                        
                        return 0
                    
                    ans = dp(curr, remain - 1)
                    if curr > 0:
                        ans = (ans + dp(curr - 1, remain - 1)) % MOD
                    
                    if curr < arrLen - 1:
                        ans = (ans + dp(curr + 1, remain - 1)) % MOD
                        
                    return ans
                
                MOD = 10 ** 9 + 7
                return dp(0, steps)
        

        4.7.1103 - 2023-10-14 19:53:26 +0300 MSK

        Painting the Walls

        Code

        class Solution:
            def paintWalls(self, cost: List[int], time: List[int]) -> int:
                @cache
                def dp(i, remain):
                    if remain <= 0:
                        return 0
                    if i == n:
                        return inf
                    
                    paint = cost[i] + dp(i + 1, remain - 1 - time[i])
                    dont_paint = dp(i + 1, remain)
                    return min(paint, dont_paint)
            
                n = len(cost)
                return dp(0, n)
        

        4.7.1104 - 2023-10-14 10:14:40 +0300 MSK

        Min Cost Climbing Stairs

        Code

        class Solution:
            def minCostClimbingStairs(self, cost):
                n = len(cost)
                dp = [0] * n
                dp[0] = cost[0]
                dp[1] = cost[1]
                
                for i in range(2, n):
                    dp[i] = cost[i] + min(dp[i-1], dp[i-2])
                
                return min(dp[n-1], dp[n-2])
        

        4.7.1105 - 2023-10-12 12:09:45 +0300 MSK

        Find in Mountain Array

        Code

        class Solution:
            def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
                # Save the length of the mountain array
                length = mountain_arr.length()
        
                # 1. Find the index of the peak element
                low = 1
                high = length - 2
                while low != high:
                    test_index = (low + high) // 2
                    if mountain_arr.get(test_index) < mountain_arr.get(test_index + 1):
                        low = test_index + 1
                    else:
                        high = test_index
                peak_index = low
        
                # 2. Search in the strictly increasing part of the array
                low = 0
                high = peak_index
                while low != high:
                    test_index = (low + high) // 2
                    if mountain_arr.get(test_index) < target:
                        low = test_index + 1
                    else:
                        high = test_index    
                # Check if the target is present in the strictly increasing part
                if mountain_arr.get(low) == target:
                    return low
                
                # 3. Otherwise, search in the strictly decreasing part
                low = peak_index + 1
                high = length - 1
                while low != high:
                    test_index = (low + high) // 2
                    if mountain_arr.get(test_index) > target:
                        low = test_index + 1
                    else:
                        high = test_index
                # Check if the target is present in the strictly decreasing part
                if mountain_arr.get(low) == target:
                    return low
                
                # Target is not present in the mountain array
                return -1
        

        4.7.1106 - 2023-10-11 16:06:35 +0300 MSK

        Number of Flowers in Full Bloom

        Code

        class Solution:
            def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:
                flowers.sort()
                sorted_people = sorted(people)
                dic = {}
                heap = []
                
                i = 0
                for person in sorted_people:
                    while i < len(flowers) and flowers[i][0] <= person:
                        heapq.heappush(heap, flowers[i][1])
                        i += 1
                    
                    while heap and heap[0] < person:
                        heapq.heappop(heap)
                    
                    dic[person] = len(heap)
        
                return [dic[x] for x in people]
        

        4.7.1107 - 2023-10-10 08:23:28 +0300 MSK

        Minimum Number of Operations to Make Array Continuous

        Code

        class Solution:
            def minOperations(self, nums: List[int]) -> int:
                n = len(nums)
                ans = n
                new_nums = sorted(set(nums))
                
                for i in range(len(new_nums)):
                    left = new_nums[i]
                    right = left + n - 1
                    j = bisect_right(new_nums, right)
                    count = j - i
                    ans = min(ans, n - count)
        
                return ans
        

        4.7.1108 - 2023-10-09 14:15:25 +0300 MSK

        Find First and Last Position of Element in Sorted Array

        Code

        class Solution:
            def searchRange(self, nums: List[int], target: int) -> List[int]:
                def binary_search(nums, target, left):
                    low, high = 0, len(nums) - 1
                    index = -1
                    while low <= high:
                        mid = (low + high) // 2
                        if nums[mid] == target:
                            index = mid
                            if left:
                                high = mid - 1
                            else:
                                low = mid + 1
                        elif nums[mid] < target:
                            low = mid + 1
                        else:
                            high = mid - 1
                    return index
        
                left_index = binary_search(nums, target, left=True)
                right_index = binary_search(nums, target, left=False)
        
                return [left_index, right_index]
        

        4.7.1109 - 2023-10-08 10:39:44 +0300 MSK

        Max Dot Product of Two Subsequences

        Code

        class Solution:
            def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
                @cache
                def dp(i, j):
                    if i == len(nums1) or j == len(nums2):
                        return 0
                    
                    use = nums1[i] * nums2[j] + dp(i + 1, j + 1)
                    return max(use, dp(i + 1, j), dp(i, j + 1))
                    
                if max(nums1) < 0 and min(nums2) > 0:
                    return max(nums1) * min(nums2)
                
                if min(nums1) > 0 and max(nums2) < 0:
                    return min(nums1) * max(nums2)
                
                return dp(0, 0)
        

        4.7.1110 - 2023-10-07 19:48:10 +0300 MSK

        Build Array Where You Can Find The Maximum Exactly K Comparisons

        Code

        class Solution:
            def numOfArrays(self, n: int, m: int, k: int) -> int:
                @cache
                def dp(i, max_so_far, remain):
                    if i == n:
                        if remain == 0:
                            return 1
                        
                        return 0
                    
                    ans = (max_so_far * dp(i + 1, max_so_far, remain)) % MOD
                    for num in range(max_so_far + 1, m + 1):
                        ans = (ans + dp(i + 1, num, remain - 1)) % MOD
                        
                    return ans
                
                MOD = 10 ** 9 + 7
                return dp(0, 0, k)
        

        4.7.1111 - 2023-10-06 12:24:39 +0300 MSK

        Integer Break

        Code

        class Solution:
            def integerBreak(self, n: int) -> int:
                if n < 4:
                    return n - 1
                
                @cache
                def dp(num: int) -> int:
                    if num <= 3:
                        return num
                    ans = num
                    for i in range(2, num):
                        ans = max(ans, i * dp(num - i))
                    return ans
        
                return dp(n)
        

        4.7.1112 - 2023-10-06 12:24:09 +0300 MSK

        Integer Break

        Code

        class Solution:
            def integerBreak(self, n: int) -> int:
                @cache
                def dp(num: int) -> int:
                    if num <= 3:
                        return num
                    ans = num
                    for i in range(2, num):
                        ans = max(ans, i * dp(num - i))
                    return ans
        
                return dp(n) if n > 3 else n - 1
        

        4.7.1113 - 2023-10-05 09:46:37 +0300 MSK

        Majority Element II

        Code

        class Solution:
            def majorityElement(self, nums: List[int]) -> List[int]:
                nums.sort()
                threshold = len(nums) // 3
                cur_num, cur_count = nums[0], 1
                answer = []
                for num in nums[1:]:
                    if num == cur_num:
                        cur_count += 1
                        continue
                    if cur_count > threshold:
                        answer.append(cur_num)
                    cur_num, cur_count = num, 1
                if cur_count > threshold:
                    answer.append(cur_num)
                return answer
        

        4.7.1114 - 2023-10-04 09:00:01 +0300 MSK

        Design HashMap

        Code

        class ListNode:
            def __init__(self, key, value):
                self.key = key
                self.value = value
                self.next = None
        
        class MyHashMap:
        
            def __init__(self):
                self.size = 1000
                self.table = [None] * self.size
        
            def _index(self, key: int) -> int:
                return key % self.size
        
            def put(self, key: int, value: int) -> None:
                idx = self._index(key)
                if not self.table[idx]:
                    self.table[idx] = ListNode(key, value)
                    return
                current = self.table[idx]
                while current:
                    if current.key == key:
                        current.value = value
                        return
                    if not current.next:
                        current.next = ListNode(key, value)
                        return
                    current = current.next
        
            def get(self, key: int) -> int:
                idx = self._index(key)
                current = self.table[idx]
                while current:
                    if current.key == key:
                        return current.value
                    current = current.next
                return -1
        
            def remove(self, key: int) -> None:
                idx = self._index(key)
                current = self.table[idx]
                if not current:
                    return
                if current.key == key:
                    self.table[idx] = current.next
                    return
                while current.next:
                    if current.next.key == key:
                        current.next = current.next.next
                        return
                    current = current.next
        
        
        # Your MyHashMap object will be instantiated and called as such:
        # obj = MyHashMap()
        # obj.put(key,value)
        # param_2 = obj.get(key)
        # obj.remove(key)
        

        4.7.1115 - 2023-10-04 08:57:26 +0300 MSK

        Design HashMap

        Code

        class MyHashMap:
            def __init__(self):
                self.data = [None] * 1000001
        
            def put(self, key: int, val: int) -> None:
                self.data[key] = val
                
            def get(self, key: int) -> int:
                val = self.data[key]
                return -1 if val is None else val
        
            def remove(self, key: int) -> None:
                self.data[key] = None
                
        
        
        # Your MyHashMap object will be instantiated and called as such:
        # obj = MyHashMap()
        # obj.put(key,value)
        # param_2 = obj.get(key)
        # obj.remove(key)
        

        4.7.1116 - 2023-10-03 09:14:03 +0300 MSK

        Number of Good Pairs

        Code

        class Solution:
            def numIdenticalPairs(self, nums: List[int]) -> int:
                counter = Counter(nums)
                return sum((count ** 2 - count) // 2 for count in counter.values() if count > 1)
        

        4.7.1117 - 2023-10-03 09:13:40 +0300 MSK

        Number of Good Pairs

        Code

        class Solution:
            def numIdenticalPairs(self, nums: List[int]) -> int:        
                return sum((count ** 2 - count) // 2 for count in Counter(nums).values() if count > 1)
        

        4.7.1118 - 2023-10-03 09:13:11 +0300 MSK

        Number of Good Pairs

        Code

        class Solution:
            def numIdenticalPairs(self, nums: List[int]) -> int:
                counter = Counter(nums)
                
                return sum((count ** 2 - count) // 2 for count in counter.values() if count > 1)
        

        4.7.1119 - 2023-10-02 15:20:53 +0300 MSK

        Remove Colored Pieces if Both Neighbors are the Same Color

        Code

        class Solution:
            def winnerOfGame(self, colors: str) -> bool:
                cur_char, cur_conseq = colors[0], 1
                moves = {"A": 0, "B": 0}
                for char in colors[1:]:
                    if char == cur_char:
                        cur_conseq += 1
                    else:
                        moves[cur_char] += max(0, cur_conseq - 2)
                        cur_char, cur_conseq = char, 1
                if cur_conseq > 2:
                    moves[cur_char] += cur_conseq - 2
                return moves["A"] > moves["B"]
        

        4.7.1120 - 2023-10-01 16:29:08 +0300 MSK

        Reverse Words in a String III

        Code

        class Solution:
            def reverseWords(self, s: str) -> str:
                return ' '.join(map(lambda word: word[::-1], s.split()))
        

        4.7.1121 - 2023-09-30 10:17:26 +0300 MSK

        Merge Intervals

        Code

        class Solution:
            def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        
                intervals.sort(key=lambda item: item[0])
        
                merged = []
                for start, end in intervals:
                    # if the list of merged intervals is empty or if the current
                    # interval does not overlap with the previous, simply append it.
                    if not merged or merged[-1][1] < start:
                        merged.append([start, end])
                    else:
                    # otherwise, there is overlap, so we merge the current and previous
                    # intervals.
                        merged[-1][1] = max(merged[-1][1], end)
        
                return merged
        

        4.7.1122 - 2023-09-30 10:09:04 +0300 MSK

        132 Pattern

        Code

        class Solution:
            def find132pattern(self, nums: List[int]) -> bool:
                if len(nums) < 3:
                    return False
                min_array = [-1] * len(nums)
                min_array[0] = nums[0]
                for i in range(1, len(nums)):
                    min_array[i] = min(min_array[i - 1], nums[i])
        
                k = len(nums)
                for j in range(len(nums) - 1, -1, -1):
                    if nums[j] <= min_array[j]:
                        continue
                    while k < len(nums) and nums[k] <= min_array[j]:
                        k += 1
                    if k < len(nums) and nums[k] < nums[j]:
                        return True
                    k -= 1
                    nums[k] = nums[j]
                return False
        

        4.7.1123 - 2023-09-30 10:05:56 +0300 MSK

        132 Pattern

        Code

        class Solution:
            def find132pattern(self, nums: List[int]) -> bool:
                if len(nums) < 3:
                    return False
                stack = []
                min_array = [-1] * len(nums)
                min_array[0] = nums[0]
                for i in range(1, len(nums)):
                    min_array[i] = min(min_array[i - 1], nums[i])
        
                for j in reversed(range(len(nums))):
                    if nums[j] <= min_array[j]:
                        continue
                    while stack and stack[-1] <= min_array[j]:
                        stack.pop()
                    if stack and stack[-1] < nums[j]:
                        return True
                    stack.append(nums[j])
                return False
        

        4.7.1124 - 2023-09-29 08:36:09 +0300 MSK

        Monotonic Array

        Code

        class Solution:
            def isMonotonic(self, nums: List[int]) -> bool:
                length = len(nums)
                if length < 3:
                    return True
                is_increasing = None
                for i in range(1, length):
                    cur, prev = nums[i], nums[i-1]
                    if cur == prev:
                        continue
                    is_increasing_cur = cur > prev
                    if is_increasing is None:
                        is_increasing = is_increasing_cur
                        continue
                    if is_increasing and not is_increasing_cur or (
                        not is_increasing and is_increasing_cur
                    ):
                        return False
                return True
        

        4.7.1125 - 2023-09-28 10:17:33 +0300 MSK

        Sort Array By Parity

        Code

        class Solution:
            def sortArrayByParity(self, nums: List[int]) -> List[int]:
                left, right = 0, len(nums) - 1
                while left < right:
                    while left < right and nums[left] % 2 == 0:
                        left += 1
                    while left < right and nums[right] % 2 == 1:
                        right -= 1
                    nums[left], nums[right] = nums[right], nums[left]
                return nums
        

        4.7.1126 - 2023-09-28 10:13:16 +0300 MSK

        Sort Array By Parity

        Code

        class Solution:
            def sortArrayByParity(self, nums: List[int]) -> List[int]:
                length = len(nums)
                left, right = 0, length - 1
                answer = [None] * length
                for num in nums:
                    if num % 2 == 0:
                        answer[left] = num
                        left += 1
                    else:
                        answer[right] = num
                        right -= 1
                return answer
        

        4.7.1127 - 2023-09-27 18:11:20 +0300 MSK

        Decoded String at Index

        Code

        class Solution:
            def decodeAtIndex(self, s: str, k: int) -> str:
                length = 0
                i = 0
                
                while length < k:
                    if s[i].isdigit():
                        length *= int(s[i])
                    else:
                        length += 1
                    i += 1
                
                for j in range(i-1, -1, -1):
                    char = s[j]
                    if char.isdigit():
                        length //= int(char)
                        k %= length
                    else:
                        if k == 0 or k == length:
                            return char
                        length -= 1
        

        4.7.1128 - 2023-09-26 13:43:09 +0300 MSK

        Remove Duplicate Letters

        Code

        class Solution:
            def removeDuplicateLetters(self, s: str) -> str:
                stack = []
                seen = set() 
                last_occ = {char: i for i, char in enumerate(s)}
                
                for i, char in enumerate(s):
                    if char in seen:
                        continue
                        
                    while stack and char < stack[-1] and i < last_occ[stack[-1]]:
                        seen.discard(stack.pop())
                    seen.add(char)
                    stack.append(char)
                
                return ''.join(stack)
        

        4.7.1129 - 2023-09-25 09:17:00 +0300 MSK

        Find Minimum in Rotated Sorted Array

        Code

        class Solution:
            def findMin(self, nums: List[int]) -> int:
                length = len(nums)
                if length == 1:
                    return nums[0]
                first, last = nums[0], nums[-1]
                if first < last:
                    return first
                left, right = 0, length - 1
                while left <= right:
                    mid = left + (right - left) // 2
                    left_num = nums[mid - 1] if mid > 0 else first
                    mid_num = nums[mid] 
                    right_num = nums[mid + 1] if mid + 1 < length else last
                    if left_num > mid_num <= right_num:
                        return mid_num
                    if left_num > mid_num or (left_num <= mid_num and mid_num >= first):
                        left = mid + 1
                    else:
                        right = mid
                return nums[left]
        

        4.7.1130 - 2023-09-25 08:28:38 +0300 MSK

        Find the Difference

        Code

        class Solution:
            def findTheDifference(self, s: str, t: str) -> str:
                return chr(reduce(operator.xor, (ord(char) for char in chain(s, t))))
        

        4.7.1131 - 2023-09-25 08:26:39 +0300 MSK

        Find the Difference

        Code

        class Solution:
            def findTheDifference(self, s: str, t: str) -> str:
                count = Counter(s)
                for char in t:
                    count[char] -= 1
                    if count[char] == -1:
                        return char
        

        4.7.1132 - 2023-09-24 14:37:54 +0300 MSK

        Bitwise AND of Numbers Range

        Code

        class Solution:
            def rangeBitwiseAnd(self, left: int, right: int) -> int:
                shift = 0        
                while left < right:
                    left >>= 1
                    right >>= 1
                    shift += 1
                return left << shift
        

        4.7.1133 - 2023-09-24 13:28:55 +0300 MSK

        Container With Most Water

        Code

        class Solution:
            def maxArea(self, height: List[int]) -> int:
                left = 0
                right = len(height) - 1
                maxArea = 0
        
                while left < right:
                    currentArea = min(height[left], height[right]) * (right - left)
                    if currentArea > maxArea:
                        maxArea = currentArea
        
                    if height[left] < height[right]:
                        left += 1
                    else:
                        right -= 1
        
                return maxArea
        

        4.7.1134 - 2023-09-24 13:26:28 +0300 MSK

        Max Points on a Line

        Code

        class Solution:
            def maxPoints(self, points: List[List[int]]) -> int:
                lines = defaultdict(set)
                length = len(points)
                if length < 3:
                    return length
                for i in range(length):
                    x1, y1 = points[i]
                    for j in range(i + 1, length):
                        x2, y2 = points[j]
                        k1, k2 = None, None
                        if y1 == y2:
                            k2 = y1
                        elif x1 == x2:
                            k1 = x1
                        else: 
                            k1 = (y2 - y1) / (x2 - x1)
                            k2 = y1 - k1 * x1
                        lines[(k1, k2)].update(((x1, y1), (x2, y2)))
                return max((len(points) for points in lines.values()), default=0)
        

        4.7.1135 - 2023-09-24 13:00:11 +0300 MSK

        Candy

        Code

        class Solution:
            def candy(self, ratings: List[int]) -> int:
                child_count = len(ratings)
                candies = [1] * child_count 
        
                for i in range(1, child_count):
                    if ratings[i] > ratings[i-1]:
                        candies[i] = candies[i-1] + 1
        
                for i in reversed(range(child_count - 1)):
                    if ratings[i] > ratings[i+1]:
                        candies[i] = max(candies[i], candies[i+1] + 1)
                
                return sum(candies)
        

        4.7.1136 - 2023-09-24 12:59:51 +0300 MSK

        Longest Substring Without Repeating Characters

        Code

        class Solution:
            def lengthOfLongestSubstring(self, s: str) -> int:
                length = len(s)
                if length < 2:
                    return length
                
                max_length, left, charset = 1, 0, set([s[0]])
                for right in range(1, length):
                    letter = s[right]
                    if letter not in charset:
                        charset.add(letter)
                        continue
        
                    this_length = right - left
                    if this_length > max_length:
                        max_length = this_length
                    
                    while letter in charset:
                        charset.remove(s[left])
                        left += 1
                    
                    charset.add(letter)
        
                return max(max_length, length - left)
        

        4.7.1137 - 2023-09-24 12:59:24 +0300 MSK

        Populating Next Right Pointers in Each Node II

        Code

        from collections import deque
        
        class Solution:
          def connect(self, root: 'Node') -> 'Node':
            # Edge case - If the root is None, then return None
            if root is None:
                return None
            
            # Create a queue and enqueue the root node
            q = deque([root])
            
            # Traverse the tree level by level
            while q:
                
                # Get the number of nodes of the current level
                level_size = len(q)
                
                # Process the nodes of the current level
                for i in range(level_size):
                    
                    # Dequeue a node from the front of the queue
                    node = q.popleft()
                    
                    # Assign the next pointer of the node
                    if i < level_size - 1:
                        node.next = q[0]
                    
                    # Enqueue the children of the node (if any)
                    if node.left is not None:
                        q.append(node.left)
                    if node.right is not None:
                        q.append(node.right)
            
            # Return the root node
            return root
        

        4.7.1138 - 2023-09-24 12:56:43 +0300 MSK

        Binary Search Tree Iterator

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class BSTIterator:
        
            def __init__(self, root: Optional[TreeNode]):
                def generate(node: TreeNode) -> int:
                    if not node:
                        return
                    yield from generate(node.left)
                    yield node
                    yield from generate(node.right)
        
                self._generate = generate(root)
                self._next = next(self._generate)
        
            def next(self) -> int:
                next_val = self._next.val
                self._next = next(self._generate, None)
                return next_val 
        
            def hasNext(self) -> bool:
                return self._next is not None
        
        
        # Your BSTIterator object will be instantiated and called as such:
        # obj = BSTIterator(root)
        # param_1 = obj.next()
        # param_2 = obj.hasNext()
        

        4.7.1139 - 2023-09-24 12:56:22 +0300 MSK

        Implement Trie (Prefix Tree)

        Code

        class Trie:
        
            def __init__(self):
                self.root = {}
        
            def insert(self, word: str) -> None:
                cur = self.root
                for char in word:
                    if char not in cur:
                        cur[char] = {}
                    cur = cur[char]
                
                cur["_is_word"] = None
        
            def search(self, word: str) -> bool:
                cur = self.root
                for char in word:
                    if char not in cur:
                        return False
                    cur = cur[char]
                
                return "_is_word" in cur
        
            def startsWith(self, prefix: str) -> bool:
                cur = self.root
                for char in prefix:
                    if char not in cur:
                        return False
                    cur = cur[char]
                    
                return True
        
        
        # Your Trie object will be instantiated and called as such:
        # obj = Trie()
        # obj.insert(word)
        # param_2 = obj.search(word)
        # param_3 = obj.startsWith(prefix)
        

        4.7.1140 - 2023-09-24 12:55:57 +0300 MSK

        Combinations

        Code

        class Solution:
            def combine(self, n: int, k: int) -> List[List[int]]:
                current = []
                
                def backtrack(first: int) -> Generator[None, None, List[int]]:
                    if len(current) == k:
                        yield tuple(current[:])
                        return
        
                    for i in range(first, n + 1):
                        current.append(i)
                        yield from backtrack(i + 1)
                        current.pop()
                    
                    return
        
                return tuple(combination for combination in backtrack(1)) 
        

        4.7.1141 - 2023-09-24 12:55:41 +0300 MSK

        Permutations

        Code

        class Solution:
            def permute(self, nums: List[int]) -> List[List[int]]:
        
                length = len(nums)
                current = []
                current_contains = [False] * length
        
                def backtrack() -> Generator[None, None, List[int]]:
                    if len(current) == length:
                        yield tuple(current[:])
                        return
        
                    for i in range(length):
                        if current_contains[i]:
                            continue
        
                        current_contains[i] = True
                        current.append(nums[i])
        
                        yield from backtrack()
        
                        current_contains[i] = False
                        current.pop()
                    
                    return
        
                return tuple(combination for combination in backtrack()) 
        

        4.7.1142 - 2023-09-24 12:55:19 +0300 MSK

        Generate Parentheses

        Code

        class Solution:
            def generateParenthesis(self, n: int) -> List[str]:
        
                current = []
                current_max = n * 2
                chars = "()"
        
        
                def backtrack(open: int, closed: int) -> Generator[None, None, List[str]]:
                    if len(current) == current_max:
                        yield "".join(current)
                    
                    if open:
                        current.append(chars[0])
                        yield from backtrack(open - 1, closed)
                        current.pop()
                    
                    if closed and closed > open:
                        current.append(chars[1])
                        yield from backtrack(open, closed - 1)
                        current.pop()
                
                return tuple(combination for combination in backtrack(n, n))
        

        4.7.1143 - 2023-09-24 12:54:51 +0300 MSK

        Maximum Subarray

        Code

        class Solution:
            def maxSubArray(self, nums: List[int]) -> int:
                length = len(nums)
                if length == 0:
                    return 0
                if length == 1:
                    return nums[0]
                max_cur, max_overall = 0, float("-inf")
                for num in nums:
                    max_cur += num
                    if max_cur > max_overall:
                        max_overall = max_cur
                    if max_cur < 0:
                        max_cur = 0
                return max_overall
                
        

        4.7.1144 - 2023-09-24 12:53:12 +0300 MSK

        Median of Two Sorted Arrays

        Code

        class Solution:
            def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
                m, n = len(nums1), len(nums2)
                p1, p2 = 0, 0
                
                # Get the smaller value between nums1[p1] and nums2[p2].
                def get_min():
                    nonlocal p1, p2
                    if p1 < m and p2 < n:
                        if nums1[p1] < nums2[p2]:
                            ans = nums1[p1]
                            p1 += 1
                        else:
                            ans = nums2[p2]
                            p2 += 1
                    elif p2 == n:
                        ans = nums1[p1]
                        p1 += 1
                    else:
                        ans = nums2[p2]
                        p2 += 1
                    return ans
                
                if (m + n) % 2 == 0:
                    for _ in range((m + n) // 2 - 1):
                        _ = get_min()
                    return (get_min() + get_min()) / 2
                else:
                    for _ in range((m + n) // 2):
                        _ = get_min()
                    return get_min()
        

        4.7.1145 - 2023-09-24 12:52:56 +0300 MSK

        Search in Rotated Sorted Array

        Code

        class Solution:
            def search(self, nums: List[int], target: int) -> int:
                nums_count = len(nums)
                left, right = 0, len(nums) - 1
        
                first_num, last_num = nums[0], nums[-1]
                if first_num == target:
                    return 0
                if last_num == target:
                    return nums_count - 1
                
                # Find the index of the pivot element (the smallest element)
                while left <= right:
                    mid = left + (right - left) // 2
                    if nums[mid] > last_num:
                        left = mid + 1
                    else:
                        right = mid - 1
                
                pivot_num = nums[left]
                if pivot_num == target:
                    return left
                
                if pivot_num < target < last_num:
                    right = nums_count - 1
                else:
                    left = 0
                
                while left <= right:
                    mid = left + (right - left) // 2
                    mid_num = nums[mid]
                    if mid_num == target:
                        return mid
                    elif mid_num > target:
                        right = mid - 1
                    else:
                        left = mid + 1
                
                return -1
        

        4.7.1146 - 2023-09-24 12:52:34 +0300 MSK

        Single Number II

        Code

        class Solution:
            def singleNumber(self, nums: List[int]) -> int:
                nums.sort()
                length = len(nums)
                for i in range(0, length, 3):
                    if i == length - 1:
                        return nums[i]
            
                    num_1, num_2, num_3 = nums[i], nums[i+1], nums[i+2]
        
                    if num_1 == num_2 == num_3:
                        continue
                    
                    if num_2 == num_3:
                        return num_1
                    
                    if num_1 == num_3:
                        return num_2
                    
                    return num_3
                    
        

        4.7.1147 - 2023-09-24 12:52:13 +0300 MSK

        Single Number

        Code

        class Solution:
            def singleNumber(self, nums: List[int]) -> int:
                return reduce(xor, nums)
        

        4.7.1148 - 2023-09-24 12:51:48 +0300 MSK

        Number of 1 Bits

        Code

        class Solution:
            def hammingWeight(self, n: int) -> int:
                count = 0
                while n > 0:
                    if n & 1 != 0:
                        count += 1
                    n >>= 1
                return count
        

        4.7.1149 - 2023-09-24 12:50:52 +0300 MSK

        Reverse Bits

        Code

        class Solution:
            def reverseBits(self, n: int) -> int:
                # Initialize the reversed number to 0
                reversed_num = 0
                
                # Iterate over all 32 bits of the given number
                for i in range(32):
                    # Left shift the reversed number by 1 and add the last bit of the given number to it
                    reversed_num = (reversed_num << 1) | (n & 1)
                    # remove the last bit from the original number
                    n >>= 1
                
                # Return the reversed number
                return reversed_num
        

        4.7.1150 - 2023-09-24 12:50:33 +0300 MSK

        Add Binary

        Code

        class Solution:
            def addBinary(self, a: str, b: str) -> str:
                answer = []
                carry = 0
                for char1, char2 in zip_longest(reversed(a), reversed(b)):
                    num1, num2 = int(char1) if char1 else 0, int(char2) if char2 else 0
                    cur_sum = num1 + num2 + carry
                    carry = 0
                    if cur_sum > 1:
                        cur_sum -= 2
                        carry = 1
                    
                    answer.append(str(cur_sum))
                
                if carry:
                    answer.append("1")
        
                return "".join(reversed(answer))
        

        4.7.1151 - 2023-09-24 12:47:07 +0300 MSK

        Factorial Trailing Zeroes

        Code

        class Solution:
            def trailingZeroes(self, n: int) -> int:
                zeros = 0
                while n != 0:
                    new_n = n // 5
                    zeros += new_n
                    n = new_n
                return zeros
                
        

        4.7.1152 - 2023-09-24 12:44:33 +0300 MSK

        Factorial Trailing Zeroes

        Code

        class Solution:
            def trailingZeroes(self, n: int) -> int:
                a, b, zeros = 1, 5, 0
                while (5**a) <= n:
                    zeros += n // b
                    a += 1
                    b *= 5
                return zeros
        

        4.7.1153 - 2023-09-24 12:41:55 +0300 MSK

        Pow(x, n)

        Code

        class Solution:
            def myPow(self, x: float, n: int) -> float:
                if n == 0:
                    return 1
        
                if n < 0:
                    n *= -1
                    x = 1 / x
        
                result = 1
                while n:
                    if n % 2:
                        result *= x
                        n -= 1
                    x *= x
                    n //= 2
                
                return result
        

        4.7.1154 - 2023-09-24 12:41:37 +0300 MSK

        Plus One

        Code

        class Solution:
            def plusOne(self, digits: List[int]) -> List[int]:
                carry = 1
                for i in reversed(range(len(digits))):
                    new_digit = digits[i] + carry
                    if new_digit > 9:
                        carry = 1
                        new_digit %= 10
                    else:
                        carry = 0
                    digits[i] = new_digit
                
                if carry:
                    digits.insert(0, carry)
                
                return digits
        

        4.7.1155 - 2023-09-24 12:40:45 +0300 MSK

        Partition List

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
                before_head, after_head = ListNode(0), ListNode(0)
                before_tail, after_tail = before_head, after_head
                
                while head: 
                    if head.val < x:
                        before_tail.next, before_tail = head, head
                    else:
                        after_tail.next, after_tail = head, head
                    head = head.next
                
                after_tail.next, before_tail.next = None, after_head.next
                
                return before_head.next
        

        4.7.1156 - 2023-09-24 12:40:14 +0300 MSK

        Reverse Linked List II

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
                cur_node = 1
                left_head, left_tail = head if left > 1 else None, None
        
                while cur_node < left:
                    cur_node += 1
                    head, left_tail = head.next, head
        
                cur_node += 1
                mid_head, mid_tail, head = head, head, head.next
                mid_head.next = None
        
                while cur_node <= right:
                    cur_node += 1
                    mid_head, head.next, head = head, mid_head, head.next
            
                mid_tail.next = head
                if left_head:
                    left_tail.next = mid_head
                else:
                    left_head = mid_head
        
                return left_head
        

        4.7.1157 - 2023-09-24 12:39:52 +0300 MSK

        Copy List with Random Pointer

        Code

        """
        # Definition for a Node.
        class Node:
            def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
                self.val = int(x)
                self.next = next
                self.random = random
        """
        
        class Solution:
            def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
                
                copied = {None: None}
        
                def copy_node(node: Node) -> Node:
                    if node in copied:
                        return copied[node]
                    
                    new_node = Node(node.val)
                    copied[node] = new_node
                    new_node.next = copy_node(node.next)
                    new_node.random = copy_node(node.random)
                    return new_node
                
                return copy_node(head)
        

        4.7.1158 - 2023-09-24 12:38:31 +0300 MSK

        Remove Duplicates from Sorted List II

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
                tail, before_tail = head, None
                remove_tail = False
                while tail:
                    if tail.next and tail.val == tail.next.val:
                        tail.next = tail.next.next
                        remove_tail = True
                        continue
                    if not remove_tail:
                        before_tail, tail = tail, tail.next
                        continue
                    remove_tail = False
                    if before_tail is None:
                        tail = head.next
                        head.next, head = None, head.next
                    else:
                        before_tail.next = tail.next
                        tail = tail.next
                return head
        

        4.7.1159 - 2023-09-24 12:09:18 +0300 MSK

        Champagne Tower

        Code

        class Solution:
            def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
                if query_row == 0:
                    return min(1, poured)
                if query_glass in (0, query_row):
                    while query_row and poured:
                        poured = (poured - 1) / 2 if poured > 1 else 0
                        query_row -= 1
                    return min(1, poured)
        
                cur_row, next_row = [0] * (query_row + 2), [0] * (query_row + 2)
                cur_row[0] = poured
                for row in range(query_row + 1):
                    next_row[0] = 0
                    for col in range(row + 1):
                        overflow = (cur_row[col] - 1) / 2
                        if overflow > 0:
                            next_row[col] += overflow
                            next_row[col + 1] = overflow
                        else:
                            next_row[col + 1] = 0
                    cur_row, next_row = next_row, cur_row
                return min(1, next_row[query_glass])
        

        4.7.1160 - 2023-09-23 21:54:59 +0300 MSK

        Remove Nth Node From End of List

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
                cur_length, target_length, before_removed = 0, n + 1, head
                tail = head
                while tail and cur_length != target_length:
                    tail = tail.next
                    cur_length += 1
                if not tail and cur_length != target_length:
                    return head.next
                while tail:
                    before_removed = before_removed.next
                    tail = tail.next
                before_removed.next = before_removed.next.next
                return head
        

        4.7.1161 - 2023-09-23 18:06:03 +0300 MSK

        Rotate List

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
                if k == 0 or not head:
                    return head
                temp_head, tail, length = head, head, 0
                while temp_head:
                    length += 1
                    tail, temp_head = temp_head, temp_head.next
                rotation = k % length
                if rotation == 0:
                    return head
                new_head_idx = length - rotation
                new_tail_idx = new_head_idx - 1 
                i, new_head, new_tail = 0, None, None
                temp_head = head
                while temp_head:
                    if i == new_head_idx:
                        new_head = temp_head
                        break
                    if i == new_tail_idx:
                        new_tail = temp_head
                    i += 1
                    temp_head = temp_head.next
                tail.next = head
                new_tail.next = None
                return new_head
        
                    
        

        4.7.1162 - 2023-09-23 13:19:00 +0300 MSK

        Longest String Chain

        Code

        class Solution:
            def longestStrChain(self, words: List[str]) -> int:
                words.sort(key=len)
                dp = {}
                max_chain = 0
                for word in words:
                    dp[word] = 1
                    for i in range(len(word)):
                        prev_word = word[:i] + word[i+1:]
                        if prev_word in dp:
                            dp[word] = max(dp[word], dp[prev_word] + 1)
                    max_chain = max(max_chain, dp[word])
                return max_chain
        

        4.7.1163 - 2023-09-22 18:29:58 +0300 MSK

        Minimum Bit Flips to Convert Number

        Code

        class Solution:
            def minBitFlips(self, start: int, goal: int) -> int:
                flips_count = 0
                while start or goal:
                    start_is_one, goal_is_one = start & 1, goal & 1
                    if start_is_one and not goal_is_one or (not start_is_one and goal_is_one):
                        flips_count += 1
                    start >>= 1
                    goal >>= 1
                return flips_count
        

        4.7.1164 - 2023-09-22 13:51:50 +0300 MSK

        Sum of All Subset XOR Totals

        Code

        class Solution:
            def subsetXORSum(self, nums: List[int]) -> int:
                return reduce(operator.or_, nums) * 1 << (len(nums) - 1)
                
        

        4.7.1165 - 2023-09-22 13:49:11 +0300 MSK

        Sum of All Subset XOR Totals

        Code

        class Solution:
            def subsetXORSum(self, nums: List[int]) -> int:
                subsets_count = 2**(len(nums) - 1)
                return reduce(operator.or_, nums) * subsets_count
                
        

        4.7.1166 - 2023-09-22 12:14:22 +0300 MSK

        Longest Nice Substring

        Code

        class Solution:
            def longestNiceSubstring(self, s: str) -> str:
                sSet = set(s)
                for i in range(len(s)):
                    if s[i].lower() not in sSet or s[i].upper() not in sSet:
                        lns1 = self.longestNiceSubstring(s[:i])
                        lns2 = self.longestNiceSubstring(s[i+1:])
        
                        return max(lns1, lns2, key=len)
        
                return s
        

        4.7.1167 - 2023-09-22 11:34:42 +0300 MSK

        Count the Number of Consistent Strings

        Code

        class Solution:
            def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
                allowed = set(allowed)
                count = 0
                for word in words:
                    if all(char in allowed for char in word):
                        count += 1
                return count
        

        4.7.1168 - 2023-09-22 11:27:41 +0300 MSK

        Count the Number of Consistent Strings

        Code

        class Solution:
            def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
                allowed = set(allowed)
                count = 0
                for word in words:
                    if not set(word) - allowed:
                        count += 1
                return count
        

        4.7.1169 - 2023-09-22 11:23:55 +0300 MSK

        XOR Operation in an Array

        Code

        class Solution:
            def xorOperation(self, n: int, start: int) -> int:
                return reduce(lambda total, i: total ^ (start + 2 * i), chain((0, ), range(n)))
        

        4.7.1170 - 2023-09-22 10:24:39 +0300 MSK

        Binary Gap

        Code

        class Solution:
            def binaryGap(self, n: int) -> int:
                i, first_bit = 0, None
                max_distance = 0
                while n:
                    is_one = n & 1 == 1
                    if is_one and first_bit is None:
                        first_bit = i
                    elif is_one:
                        max_distance, first_bit = max(max_distance, i - first_bit), i
                    n >>= 1
                    i += 1
                
                return max_distance 
        

        4.7.1171 - 2023-09-22 08:57:07 +0300 MSK

        Is Subsequence

        Code

        class Solution:
            def isSubsequence(self, s: str, t: str) -> bool:
                i = 0
                length = len(s)
                for char in t:
                    if i == length:
                        break
                    if s[i] == char:
                        i += 1
                    
                return i == length
        

        4.7.1172 - 2023-09-22 08:51:25 +0300 MSK

        Prime Number of Set Bits in Binary Representation

        Code

        class Solution:
            def countPrimeSetBits(self, left: int, right: int) -> int:
                prime_bits = (2, 3, 5, 7, 11, 13, 17, 19)
                answer = 0
                for num in range(left, right + 1):
                    bit_count = num.bit_count()
                    if bit_count in prime_bits:
                        answer += 1
                    
                return answer
        

        4.7.1173 - 2023-09-21 19:36:09 +0300 MSK

        Set Mismatch

        Code

        class Solution:
            def findErrorNums(self, nums: List[int]) -> List[int]:
                length = len(nums)
                # dupl_xor_miss = duplicate ^ missing
                dupl_xor_miss = reduce(lambda total, i: total ^ i ^ nums[i - 1], range(length + 1))
                rightmost_set_bit = dupl_xor_miss & -dupl_xor_miss
                xor_group1 = xor_group2 = 0
                for i in range(1, length + 1):
                    if i & rightmost_set_bit:
                        xor_group1 ^= i
                    else:
                        xor_group2 ^= i
                    if nums[i - 1] & rightmost_set_bit:
                        xor_group1 ^= nums[i - 1]
                    else:
                        xor_group2 ^= nums[i - 1]
                for num in nums:
                    if num == xor_group1:
                        return num, xor_group2
                    if num == xor_group2:
                        return num, xor_group1 
                
                raise Exception()
        

        4.7.1174 - 2023-09-21 19:11:34 +0300 MSK

        Set Mismatch

        Code

        class Solution:
            def findErrorNums(self, nums: List[int]) -> List[int]:
                n = len(nums)
                dupl_xor_miss = 0
                for i in range(1, n+1):
                    dupl_xor_miss ^= i ^ nums[i-1]
                
                # example for get rightmost set bit
                # x:             01110000
                # ~x:            10001111
                # -x or ~x + 1:  10010000
                # x & -x:        00010000
        
                # example for unset rightmost set bit
                # x:             01110000
                # x-1:           01101111
                # x & (x-1):     01100000
                rightmost_set_bit = dupl_xor_miss & -dupl_xor_miss
                xor_group1 = xor_group2 = 0
                for i in range(1, n + 1):
                    if i & rightmost_set_bit:
                        xor_group1 ^= i
                    else:
                        xor_group2 ^= i
                    if nums[i-1] & rightmost_set_bit:
                        xor_group1 ^= nums[i-1]
                    else:
                        xor_group2 ^= nums[i-1]
                
                for num in nums:
                    if num == xor_group1:
                        return [num, xor_group2]
                    if num == xor_group2:
                        return [num, xor_group1]
        
                return []
        

        4.7.1175 - 2023-09-21 18:33:03 +0300 MSK

        Number Complement

        Code

        class Solution:
            def findComplement(self, num: int) -> int:
                return ~num + (1 << num.bit_length())
        

        4.7.1176 - 2023-09-21 09:51:52 +0300 MSK

        Median of Two Sorted Arrays

        Code

        class Solution:
            def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
                m, n = len(nums1), len(nums2)
                p1, p2 = 0, 0
                
                # Get the smaller value between nums1[p1] and nums2[p2].
                def get_min():
                    nonlocal p1, p2
                    if p1 < m and p2 < n:
                        if nums1[p1] < nums2[p2]:
                            ans = nums1[p1]
                            p1 += 1
                        else:
                            ans = nums2[p2]
                            p2 += 1
                    elif p2 == n:
                        ans = nums1[p1]
                        p1 += 1
                    else:
                        ans = nums2[p2]
                        p2 += 1
                    return ans
                
                if (m + n) % 2 == 0:
                    for _ in range((m + n) // 2 - 1):
                        _ = get_min()
                    return (get_min() + get_min()) / 2
                else:
                    for _ in range((m + n) // 2):
                        _ = get_min()
                    return get_min()
        

        4.7.1177 - 2023-09-20 22:32:26 +0300 MSK

        Sum of Values at Indices With K Set Bits

        Code

        class Solution:
            def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
                return sum(num for i, num in enumerate(nums) if i.bit_count() == k)
        

        4.7.1178 - 2023-09-20 22:28:16 +0300 MSK

        Sort Integers by The Number of 1 Bits

        Code

        class Solution:
            def sortByBits(self, arr: List[int]) -> List[int]:
                return tuple(num for num in sorted(arr, key=lambda num: (num.bit_count(), num)))
        

        4.7.1179 - 2023-09-20 22:22:48 +0300 MSK

        Number of Even and Odd Bits

        Code

        class Solution:
            def evenOddBit(self, n: int) -> List[int]:
                return (n & 0x55555555).bit_count(), (n & 0xaaaaaaaa).bit_count()
        

        4.7.1180 - 2023-09-20 22:20:17 +0300 MSK

        Number of Even and Odd Bits

        Code

        class Solution:
            def evenOddBit(self, n: int) -> List[int]:
                even, odd = n & 0x55555555, n & 0xaaaaaaaa
                even_count, odd_count = 0, 0
                while even:
                    if even & 1 == 1:
                        even_count += 1
                    even >>= 1
                    
                while odd:
                    if odd & 1 == 1:
                        odd_count += 1
                    odd >>= 1
                
                return even_count, odd_count
        

        4.7.1181 - 2023-09-20 19:50:56 +0300 MSK

        Binary Number with Alternating Bits

        Code

        class Solution:
            def hasAlternatingBits(self, n: int) -> bool:
                return n & (n >> 1) == 0 and n & (n >> 2) == n >> 2
        

        4.7.1182 - 2023-09-20 19:35:10 +0300 MSK

        Power of Three

        Code

        class Solution:
            def isPowerOfThree(self, n: int) -> bool:
                #                3 ** 20
                return n > 0 and 3486784401 % n == 0
        

        4.7.1183 - 2023-09-20 19:07:10 +0300 MSK

        Power of Two

        Code

        class Solution:
            def isPowerOfTwo(self, n: int) -> bool:
                return n > 0 and n & (n - 1) == 0
        

        4.7.1184 - 2023-09-20 18:36:36 +0300 MSK

        Power of Four

        Code

        class Solution:
            def isPowerOfFour(self, n: int) -> bool:
                # Check if the number is greater than zero and is a power of two
                if n > 0 and (n & (n - 1)) == 0:
                    # Check if the number is of the form 4^x
                    return n & 0x55555555 == n
                else:
                    return False
        

        4.7.1185 - 2023-09-20 18:32:58 +0300 MSK

        Power of Four

        Code

        class Solution:
            def isPowerOfFour(self, n: int) -> bool:
                return n and not (n & (n - 1)) and (n & 0x55555555)
        

        4.7.1186 - 2023-09-20 18:32:51 +0300 MSK

        Power of Four

        Code

        class Solution:
            def isPowerOfFour(self, n: int) -> bool:
                return n and not (n & (n - 1)) and (n & 0x55555555)
        

        4.7.1187 - 2023-09-20 18:32:34 +0300 MSK

        Power of Four

        Code

        class Solution:
            def isPowerOfFour(self, n: int) -> bool:
                return n and not (n & (n - 1)) and (n & 0x55555555)
        

        4.7.1188 - 2023-09-20 18:02:39 +0300 MSK

        Missing Number

        Code

        class Solution:
            def missingNumber(self, nums: List[int]) -> int:
                def xor(total: int, i: int) -> int:
                    return total ^ nums[i] ^ (i + 1)
                return reduce(xor, chain((0, ), range(len(nums))))
        

        4.7.1189 - 2023-09-20 18:01:50 +0300 MSK

        Missing Number

        Code

        class Solution:
            def missingNumber(self, nums: List[int]) -> int:
                return reduce(lambda total, i: total ^ nums[i] ^ (i + 1), chain((0, ), range(len(nums))))
        

        4.7.1190 - 2023-09-20 17:28:42 +0300 MSK

        Missing Number

        Code

        class Solution:
            def missingNumber(self, nums: List[int]) -> int:
                length = len(nums)
                return ((length + 1) * length) // 2 - sum(nums)
        

        4.7.1191 - 2023-09-20 17:07:50 +0300 MSK

        Reverse Bits

        Code

        class Solution:
            def reverseBits(self, n: int) -> int:
                # Initialize the reversed number to 0
                reversed_num = 0
                
                # Iterate over all 32 bits of the given number
                for i in range(32):
                    # Left shift the reversed number by 1 and add the last bit of the given number to it
                    reversed_num = (reversed_num << 1) | (n & 1)
                    # remove the last bit from the original number
                    n >>= 1
                
                # Return the reversed number
                return reversed_num
        

        4.7.1192 - 2023-09-20 16:31:32 +0300 MSK

        Add Binary

        Code

        class Solution:
            def addBinary(self, a: str, b: str) -> str:
                answer = []
                carry = 0
                for char1, char2 in zip_longest(reversed(a), reversed(b)):
                    num1, num2 = int(char1) if char1 else 0, int(char2) if char2 else 0
                    cur_sum = num1 + num2 + carry
                    carry = 0
                    if cur_sum > 1:
                        cur_sum -= 2
                        carry = 1
                    
                    answer.append(str(cur_sum))
                
                if carry:
                    answer.append("1")
        
                return "".join(reversed(answer))
        

        4.7.1193 - 2023-09-20 11:47:24 +0300 MSK

        Minimum Operations to Reduce X to Zero

        Code

        class Solution:
            def minOperations(self, nums: List[int], x: int) -> int:
                target, length = sum(nums) - x, len(nums)
                max_len = cur_sum = left = 0
                
                if target == 0:
                    return length
                
                for right, val in enumerate(nums):
                    cur_sum += val
                    while left <= right and cur_sum > target:
                        cur_sum -= nums[left]
                        left += 1
                    if cur_sum == target:
                        max_len = max(max_len, right - left + 1)
                
                return length - max_len if max_len else -1
        

        4.7.1194 - 2023-09-19 21:08:16 +0300 MSK

        Design Bitset

        Code

        class Bitset:
        
            def __init__(self, size: int):
                self.bits = [0] * size
                self.ones_count = 0
                self.do_flip = False
                self.size = size
        
            def fix(self, idx: int) -> None:
                cur = self.bits[idx]
                if self.do_flip and cur == 1:
                    self.ones_count -= 1
                    self.bits[idx] = 0
                elif not self.do_flip and cur == 0:
                    self.ones_count += 1
                    self.bits[idx] = 1
        
            def unfix(self, idx: int) -> None:
                cur = self.bits[idx]
                if self.do_flip and cur == 0:
                    self.ones_count += 1
                    self.bits[idx] = 1
                elif not self.do_flip and cur == 1:
                    self.ones_count -= 1
                    self.bits[idx] = 0
        
            def flip(self) -> None:
                self.do_flip = not self.do_flip
        
            def all(self) -> bool:
                return self.count() == self.size
        
            def one(self) -> bool:
                return self.count() > 0
        
            def count(self) -> int:
                return self.size - self.ones_count if self.do_flip else self.ones_count
        
            def toString(self) -> str:
                target = (bit ^ 1 for bit in self.bits) if self.do_flip else self.bits
                return "".join(str(num) for num in target)
        
        
        # Your Bitset object will be instantiated and called as such:
        # obj = Bitset(size)
        # obj.fix(idx)
        # obj.unfix(idx)
        # obj.flip()
        # param_4 = obj.all()
        # param_5 = obj.one()
        # param_6 = obj.count()
        # param_7 = obj.toString()
        

        4.7.1195 - 2023-09-19 20:00:19 +0300 MSK

        Find the Duplicate Number

        Code

        class Solution:
            def findDuplicate(self, nums: List[int]) -> int:
                freqs = [False] * (10**5 + 1)
                for num in nums:
                    if freqs[num] == True:
                        return num
                    freqs[num] = True
        
                raise Exception()
        

        4.7.1196 - 2023-09-19 19:58:37 +0300 MSK

        Find the Duplicate Number

        Code

        class Solution:
            def findDuplicate(self, nums: List[int]) -> int:
                freqs = [0] * (10**5 + 1)
                for num in nums:
                    freqs[num] += 1
                    if freqs[num] > 1:
                        return num
        
                raise Exception()
        

        4.7.1197 - 2023-09-18 15:46:36 +0300 MSK

        Product of the Last K Numbers

        Code

        class ProductOfNumbers:
        
            def __init__(self):
                self.products = [1]
        
            def add(self, num: int) -> None:
                if num == 0:
                    self.products.clear()
                    self.products.append(1)
                    return
                self.products.append(num * self.products[-1])
        
            def getProduct(self, k: int) -> int:
                if len(self.products) - 1 < k:
                    return 0
                return self.products[-1] // self.products[-(k + 1)]
        
        
        # Your ProductOfNumbers object will be instantiated and called as such:
        # obj = ProductOfNumbers()
        # obj.add(num)
        # param_2 = obj.getProduct(k)
        

        4.7.1198 - 2023-09-18 15:46:14 +0300 MSK

        Product of the Last K Numbers

        Code

        class ProductOfNumbers:
        
            def __init__(self):
                self.products = [1]
        
            def add(self, num: int) -> None:
                if num == 0:
                    self.products = [1]
                    return
                self.products.append(num * self.products[-1])
        
            def getProduct(self, k: int) -> int:
                if len(self.products) - 1 < k:
                    return 0
                return self.products[-1] // self.products[-(k + 1)]
        
        
        # Your ProductOfNumbers object will be instantiated and called as such:
        # obj = ProductOfNumbers()
        # obj.add(num)
        # param_2 = obj.getProduct(k)
        

        4.7.1199 - 2023-09-18 15:38:04 +0300 MSK

        Product of the Last K Numbers

        Code

        class ProductOfNumbers:
        
            def __init__(self):
                self.products, self.last_zero, self.length = [], -1, 0
        
            def add(self, num: int) -> None:
                if num == 0:
                    self.last_zero = self.length
                    num = 1
                self.products.append(num * (self.products[-1] if self.products else 1))
                self.length += 1
        
            def getProduct(self, k: int) -> int:
                first_elem = self.length - k
                if self.last_zero >= first_elem:
                    return 0
                if first_elem == 0:
                    return self.products[-1]
                return self.products[-1] // self.products[first_elem - 1]
        
        
        # Your ProductOfNumbers object will be instantiated and called as such:
        # obj = ProductOfNumbers()
        # obj.add(num)
        # param_2 = obj.getProduct(k)
        

        4.7.1200 - 2023-09-18 15:35:47 +0300 MSK

        Product of the Last K Numbers

        Code

        class ProductOfNumbers:
        
            def __init__(self):
                self.products, self.zero_indexes = [], []
        
            def add(self, num: int) -> None:
                if num == 0:
                    self.zero_indexes.append(len(self.products))
                    num = 1
                new_product = num * (self.products[-1] if self.products else 1)
                self.products.append(new_product)
        
            def getProduct(self, k: int) -> int:
                first_elem = len(self.products) - k
                if self.zero_indexes and self.zero_indexes[-1] >= first_elem:
                    return 0
                if first_elem == 0:
                    return self.products[-1]
                return self.products[-1] // self.products[first_elem - 1]
        
        
        # Your ProductOfNumbers object will be instantiated and called as such:
        # obj = ProductOfNumbers()
        # obj.add(num)
        # param_2 = obj.getProduct(k)
        

        4.7.1201 - 2023-09-18 15:12:57 +0300 MSK

        Find Consecutive Integers from a Data Stream

        Code

        class DataStream:
        
            def __init__(self, value: int, k: int):
                self.required, self.value, self.value_count = k, value, 0
        
            def consec(self, num: int) -> bool:
                if num != self.value:
                    self.value_count = 0
                    return False
                self.value_count += 1
                return self.value_count >= self.required
        
        
        # Your DataStream object will be instantiated and called as such:
        # obj = DataStream(value, k)
        # param_1 = obj.consec(num)
        

        4.7.1202 - 2023-09-18 15:12:07 +0300 MSK

        Find Consecutive Integers from a Data Stream

        Code

        class DataStream:
        
            def __init__(self, value: int, k: int):
                self.required, self.value, self.value_count = k, value, 0
                
        
            def consec(self, num: int) -> bool:
                if num != self.value:
                    self.value_count = 0
                    return False
                
                self.value_count += 1
                return self.value_count >= self.required
        
        
        # Your DataStream object will be instantiated and called as such:
        # obj = DataStream(value, k)
        # param_1 = obj.consec(num)
        

        4.7.1203 - 2023-09-18 15:00:25 +0300 MSK

        Smallest Number in Infinite Set

        Code

        class SmallestInfiniteSet:
        
            def __init__(self):
                self.heap, self.next_num, self.nums = [], 1, set() 
        
            def popSmallest(self) -> int:
                if self.heap:
                    val = heappop(self.heap)
                    self.nums.remove(val)
                    return val
                self.next_num += 1
                return self.next_num - 1
        
            def addBack(self, num: int) -> None:
                if num in self.nums or num >= self.next_num:
                    return
                self.nums.add(num)
                heappush(self.heap, num)
        
        
        # Your SmallestInfiniteSet object will be instantiated and called as such:
        # obj = SmallestInfiniteSet()
        # param_1 = obj.popSmallest()
        # obj.addBack(num)
        

        4.7.1204 - 2023-09-18 14:59:16 +0300 MSK

        Smallest Number in Infinite Set

        Code

        class SmallestInfiniteSet:
        
            def __init__(self):
                self.heap, self.next_num, self.nums = [], 1, set() 
        
        
            def popSmallest(self) -> int:
                if not self.heap:
                    self.next_num += 1
                    return self.next_num - 1
                    
                val = heappop(self.heap)
                if val < self.next_num:
                    self.nums.remove(val)
                    return val
                heappush(self.heap, val)
                self.next_num += 1
                return self.next_num - 1
                
        
            def addBack(self, num: int) -> None:
                if num in self.nums or num >= self.next_num:
                    return
                self.nums.add(num)
                heappush(self.heap, num)
        
        
        # Your SmallestInfiniteSet object will be instantiated and called as such:
        # obj = SmallestInfiniteSet()
        # param_1 = obj.popSmallest()
        # obj.addBack(num)
        

        4.7.1205 - 2023-09-18 14:37:29 +0300 MSK

        Find Elements in a Contaminated Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class FindElements:
        
            def __init__(self, root: Optional[TreeNode]):
                root.val = 0
                nodes = [root]
                self.values = set((0, )) 
                while nodes:
                    node = nodes.pop()
                    if node.left:
                        val = 2 * node.val + 1
                        node.left.val = val
                        nodes.append(node.left)
                        self.values.add(val)
                    if node.right:
                        val = 2 * node.val + 2
                        node.right.val = val
                        nodes.append(node.right)
                        self.values.add(val)
        
            def find(self, target: int) -> bool:
                return target in self.values
        
        # Your FindElements object will be instantiated and called as such:
        # obj = FindElements(root)
        # param_1 = obj.find(target)
        

        4.7.1206 - 2023-09-18 14:34:48 +0300 MSK

        Find Elements in a Contaminated Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class FindElements:
        
            def __init__(self, root: Optional[TreeNode]):
                self.root = root
                root.val = 0
                nodes = [root]
                while nodes:
                    node = nodes.pop()
                    new_val = 2 * node.val
                    if node.left:
                        node.left.val = new_val + 1
                        nodes.append(node.left)
                    if node.right:
                        node.right.val = new_val + 2
                        nodes.append(node.right)
        
            def dfs(self, node: TreeNode, target: int) -> bool:
                if not node or node.val > target:
                    return False
                if node.val == target:
                    return True
                return self.dfs(node.left, target) or self.dfs(node.right, target)
        
            def find(self, target: int) -> bool:
                return self.dfs(self.root, target)
        
        # Your FindElements object will be instantiated and called as such:
        # obj = FindElements(root)
        # param_1 = obj.find(target)
        

        4.7.1207 - 2023-09-18 13:54:11 +0300 MSK

        Range Frequency Queries

        Code

        class RangeFreqQuery:
            def __init__(self, arr: List[int]):
                self.l = [[] for _ in range(10001)]
                for i, v in enumerate(arr):
                    self.l[v].append(i)
                    
            def query(self, left: int, right: int, v: int) -> int:
                return bisect_right(self.l[v], right) - bisect_left(self.l[v], left)
        
        # Your RangeFreqQuery object will be instantiated and called as such:
        # obj = RangeFreqQuery(arr)
        # param_1 = obj.query(left,right,value)
        

        4.7.1208 - 2023-09-18 09:47:53 +0300 MSK

        The K Weakest Rows in a Matrix

        Code

        class Solution:
            def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
                rows_count, cols_count = len(mat), len(mat[0])
                heap = []
        
                for i, row in enumerate(mat):
                    count = 0
                    for j, val in enumerate(row):
                        if val == 0:
                            count = j
                            break
                    else:
                        count = cols_count
                
                    heappush(heap, (count, i))
                
                return tuple(item[1] for item in nsmallest(k, heap))
        

        4.7.1209 - 2023-09-17 16:27:05 +0300 MSK

        Implement Magic Dictionary

        Code

        class MagicDictionary:
        
            def __init__(self):
                self.dict = []
        
            def buildDict(self, dictionary: List[str]) -> None:
                self.dict = dictionary
        
            def search(self, searchWord: str) -> bool:
                target_length = len(searchWord)
                for word in self.dict:
                    if len(word) != target_length or word == searchWord:
                        continue
                    found_diff = False
                    for i in range(target_length):
                        if word[i] == searchWord[i]:
                            continue
                        if found_diff:
                            break
        
                        found_diff = True
                    else:
                        return True
        
                return False
        
        # Your MagicDictionary object will be instantiated and called as such:
        # obj = MagicDictionary()
        # obj.buildDict(dictionary)
        # param_2 = obj.search(searchWord)
        

        4.7.1210 - 2023-09-17 16:16:53 +0300 MSK

        Encode and Decode TinyURL

        Code

        class Codec:
        
            def __init__(self):
                self.urls = []
        
            def encode(self, longUrl: str) -> str:
                """Encodes a URL to a shortened URL.
                """
                self.urls.append(longUrl)
                return len(self.urls)
                
        
            def decode(self, shortUrl: str) -> str:
                """Decodes a shortened URL to its original URL.
                """
                return self.urls[shortUrl - 1]
                
        
        # Your Codec object will be instantiated and called as such:
        # codec = Codec()
        # codec.decode(codec.encode(url))
        

        4.7.1211 - 2023-09-17 16:14:59 +0300 MSK

        Encode and Decode TinyURL

        Code

        class Codec:
        
            def __init__(self):
                self.urls = {}
                self.id = 0
        
            def encode(self, longUrl: str) -> str:
                """Encodes a URL to a shortened URL.
                """
                id = self.id
                self.urls[id] = longUrl
                self.id += 1
                return id
                
        
            def decode(self, shortUrl: str) -> str:
                """Decodes a shortened URL to its original URL.
                """
                return self.urls[int(shortUrl)]
                
        
        # Your Codec object will be instantiated and called as such:
        # codec = Codec()
        # codec.decode(codec.encode(url))
        

        4.7.1212 - 2023-09-17 16:12:53 +0300 MSK

        Encode and Decode TinyURL

        Code

        class Codec:
        
            def __init__(self):
                self.urls = []
        
            def encode(self, longUrl: str) -> str:
                """Encodes a URL to a shortened URL.
                """
                self.urls.append(longUrl)
                return str(len(self.urls) - 1)
                
        
            def decode(self, shortUrl: str) -> str:
                """Decodes a shortened URL to its original URL.
                """
                return self.urls[int(shortUrl)]
                
        
        # Your Codec object will be instantiated and called as such:
        # codec = Codec()
        # codec.decode(codec.encode(url))
        

        4.7.1213 - 2023-09-17 16:08:12 +0300 MSK

        Design Twitter

        Code

        class Twitter:
        
            def __init__(self):
                self.tweets = []
                self.following = defaultdict(set)
        
            def postTweet(self, userId: int, tweetId: int) -> None:
                self.tweets.append((userId, tweetId))
        
            def getNewsFeed(self, userId: int) -> List[int]:
                tweets, following = [], self.following[userId]
                for poster, tweet in reversed(self.tweets):
                    if poster != userId and poster not in following:
                        continue
                    tweets.append(tweet)
                    if len(tweets) == 10:
                        break
                    
                return tweets
        
            def follow(self, followerId: int, followeeId: int) -> None:
                self.following[followerId].add(followeeId)
        
            def unfollow(self, followerId: int, followeeId: int) -> None:
                self.following[followerId].discard(followeeId)
        
        # Your Twitter object will be instantiated and called as such:
        # obj = Twitter()
        # obj.postTweet(userId,tweetId)
        # param_2 = obj.getNewsFeed(userId)
        # obj.follow(followerId,followeeId)
        # obj.unfollow(followerId,followeeId)
        

        4.7.1214 - 2023-09-17 11:45:39 +0300 MSK

        Shortest Path Visiting All Nodes

        Code

        from collections import deque, namedtuple
        
        class Solution:
            def shortestPathLength(self, graph):
                n = len(graph)
                all_mask = (1 << n) - 1
                visited = set()
                Node = namedtuple('Node', ['node', 'mask', 'cost'])
        
                q = deque()
                for i in range(n):
                    mask_value = (1 << i)
                    this_node = Node(i, mask_value, 1)
                    q.append(this_node)
                    visited.add((i, mask_value))
        
                while q:
                    curr = q.popleft()
        
                    if curr.mask == all_mask:
                        return curr.cost - 1
        
                    for adj in graph[curr.node]:
                        both_visited_mask = curr.mask | (1 << adj)
                        this_node = Node(adj, both_visited_mask, curr.cost + 1)
        
                        if (adj, both_visited_mask) not in visited:
                            visited.add((adj, both_visited_mask))
                            q.append(this_node)
        
                return -1
        

        4.7.1215 - 2023-09-17 11:44:04 +0300 MSK

        Implement Trie (Prefix Tree)

        Code

        class Trie:
        
            def __init__(self):
                self.root = {}
        
            def insert(self, word: str) -> None:
                cur = self.root
                for char in word:
                    if char not in cur:
                        cur[char] = {}
                    cur = cur[char]
                
                cur["_is_word"] = None
        
            def search(self, word: str) -> bool:
                cur = self.root
                for char in word:
                    if char not in cur:
                        return False
                    cur = cur[char]
                
                return "_is_word" in cur
        
            def startsWith(self, prefix: str) -> bool:
                cur = self.root
                for char in prefix:
                    if char not in cur:
                        return False
                    cur = cur[char]
                    
                return True
        
        
        # Your Trie object will be instantiated and called as such:
        # obj = Trie()
        # obj.insert(word)
        # param_2 = obj.search(word)
        # param_3 = obj.startsWith(prefix)
        

        4.7.1216 - 2023-09-17 11:40:01 +0300 MSK

        Implement Trie (Prefix Tree)

        Code

        class Node:
            def __init__(self):
                self.ch, self.is_word = [None] * 128, False
        
        class Trie:
        
            def __init__(self):
                self.head = Node()
        
            def insert(self, word: str) -> None:
                cur_node = self.head
                for i in range(len(word)):
                    char = ord(word[i])
                    if cur_node.ch[char] is None:
                        cur_node.ch[char] = Node()
                    cur_node = cur_node.ch[char]
                cur_node.is_word = True
        
            def search(self, word: str) -> bool:
                cur_node = self.head
                for i in range(len(word)):
                    char = ord(word[i])
                    if cur_node.ch[char] is None:
                        return False
                    cur_node = cur_node.ch[char]
                
                return cur_node.is_word
        
            def startsWith(self, prefix: str) -> bool:
                cur_node = self.head
                for i in range(len(prefix)):
                    char = ord(prefix[i])
                    if cur_node.ch[char] is None:
                        return False
                    cur_node = cur_node.ch[char]
                
                return True
        
        
        # Your Trie object will be instantiated and called as such:
        # obj = Trie()
        # obj.insert(word)
        # param_2 = obj.search(word)
        # param_3 = obj.startsWith(prefix)
        

        4.7.1217 - 2023-09-16 21:10:06 +0300 MSK

        Apply Discount Every n Orders

        Code

        class Cashier:
        
            def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
                self.freq, self.discount = n, (100 - discount) / 100
                self.cur = 0
                self.products = {id: price for id, price in zip(products, prices)}
        
            def getBill(self, product: List[int], amount: List[int]) -> float:
                self.cur += 1
                total = sum(amount[i] * self.products[product[i]] for i in range(len(product)))
                if self.cur < self.freq:
                    return total
                self.cur = 0
                return total * self.discount
                
        
        
        # Your Cashier object will be instantiated and called as such:
        # obj = Cashier(n, discount, products, prices)
        # param_1 = obj.getBill(product,amount)
        

        4.7.1218 - 2023-09-16 21:07:33 +0300 MSK

        Apply Discount Every n Orders

        Code

        class Cashier:
        
            def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
                self.freq, self.discount = n, (100 - discount) / 100
                self.cur = 0
                self.products = {id: price for id, price in zip(products, prices)}
        
            def getBill(self, product: List[int], amount: List[int]) -> float:
                self.cur += 1
                multiplier = 1
                if self.cur == self.freq:
                    self.cur, multiplier = 0, self.discount
                total = sum(amount[i] * self.products[product[i]] for i in range(len(product)))
                return total * multiplier
                
        
        
        # Your Cashier object will be instantiated and called as such:
        # obj = Cashier(n, discount, products, prices)
        # param_1 = obj.getBill(product,amount)
        

        4.7.1219 - 2023-09-16 20:44:34 +0300 MSK

        Design Underground System

        Code

        class UndergroundSystem:
        
            def __init__(self):
                self.from_to = defaultdict(lambda: defaultdict(list))
                self.in_transit = {}
        
            def checkIn(self, id: int, stationName: str, t: int) -> None:
                self.in_transit[id] = (stationName, t)
        
            def checkOut(self, id: int, stationName: str, t: int) -> None:
                station_from, time_from = self.in_transit.pop(id)
                self.from_to[station_from][stationName].append(t - time_from)
        
            def getAverageTime(self, startStation: str, endStation: str) -> float:
                times = self.from_to[startStation][endStation]
                return sum(times) / len(times)
        
        
        # Your UndergroundSystem object will be instantiated and called as such:
        # obj = UndergroundSystem()
        # obj.checkIn(id,stationName,t)
        # obj.checkOut(id,stationName,t)
        # param_3 = obj.getAverageTime(startStation,endStation)
        

        4.7.1220 - 2023-09-16 20:20:21 +0300 MSK

        Design an Ordered Stream

        Code

        class OrderedStream:
        
            def __init__(self, n: int):
                self.data = [None]*n
                self.ptr = 0 # 0-indexed 
        
            def insert(self, id: int, value: str) -> List[str]:
                id -= 1 # 0-indexed 
                self.data[id] = value 
                if id > self.ptr: return [] # not reaching ptr 
                
                while self.ptr < len(self.data) and self.data[self.ptr]: self.ptr += 1 # update self.ptr 
                return self.data[id:self.ptr]
        
        
        
        # Your OrderedStream object will be instantiated and called as such:
        # obj = OrderedStream(n)
        # param_1 = obj.insert(idKey,value)
        

        4.7.1221 - 2023-09-16 20:18:19 +0300 MSK

        Design an Ordered Stream

        Code

        class OrderedStream:
        
            def __init__(self, n: int):
                self.values = [None] * n
                self.length = n
                self.cur = 0
        
            def insert(self, idKey: int, value: str) -> List[str]:
                self.values[idKey - 1] = value
                for i in range(self.cur, self.length):
                    if self.values[i] is not None:
                        continue
                    
                    self.cur, answer = i, self.values[self.cur:i]
                    return answer
        
                return self.values[self.cur:]
        
        
        
        # Your OrderedStream object will be instantiated and called as such:
        # obj = OrderedStream(n)
        # param_1 = obj.insert(idKey,value)
        

        4.7.1222 - 2023-09-16 15:46:43 +0300 MSK

        Design Authentication Manager

        Code

        class AuthenticationManager:
        
            def __init__(self, timeToLive: int):
                self.ttl = timeToLive
                self.tokens = {}
        
            def generate(self, tokenId: str, currentTime: int) -> None:
                self.tokens[tokenId] = currentTime + self.ttl
        
            def renew(self, tokenId: str, currentTime: int) -> None:
                if currentTime < self.tokens.get(tokenId, currentTime):
                    self.generate(tokenId, currentTime)
                else:
                    self.tokens.pop(tokenId, None)
        
            def countUnexpiredTokens(self, currentTime: int) -> int:
                count = 0
                remove_tokens = []
                for token, expir_time in self.tokens.items():
                    if currentTime < expir_time:
                        count += 1
                    else:
                        remove_tokens.append(token)
                
                for token in remove_tokens:
                    self.tokens.pop(token)
                
                return count
        
        
        # Your AuthenticationManager object will be instantiated and called as such:
        # obj = AuthenticationManager(timeToLive)
        # obj.generate(tokenId,currentTime)
        # obj.renew(tokenId,currentTime)
        # param_3 = obj.countUnexpiredTokens(currentTime)
        

        4.7.1223 - 2023-09-16 15:35:37 +0300 MSK

        Seat Reservation Manager

        Code

        class SeatManager:
        
            def __init__(self, n: int):
                self.heap = list(range(1, n + 1))  
        
            def reserve(self) -> int:
                return heappop(self.heap)
        
            def unreserve(self, seatNumber: int) -> None:
                heappush(self.heap, seatNumber)
        
        
        # Your SeatManager object will be instantiated and called as such:
        # obj = SeatManager(n)
        # param_1 = obj.reserve()
        # obj.unreserve(seatNumber)
        

        4.7.1224 - 2023-09-16 15:34:15 +0300 MSK

        Seat Reservation Manager

        Code

        class SeatManager:
        
            def __init__(self, n: int):
                self.heap = list(range(1, n + 1))
                heapify(self.heap)        
        
            def reserve(self) -> int:
                return heappop(self.heap)
        
            def unreserve(self, seatNumber: int) -> None:
                heappush(self.heap, seatNumber)
        
        
        # Your SeatManager object will be instantiated and called as such:
        # obj = SeatManager(n)
        # param_1 = obj.reserve()
        # obj.unreserve(seatNumber)
        

        4.7.1225 - 2023-09-16 11:35:52 +0300 MSK

        Simple Bank System

        Code

        class Bank:
        
            def __init__(self, balance: List[int]):
                self.balance = balance
                self.size = len(balance)
        
            def transfer(self, account1: int, account2: int, money: int) -> bool:
                if not 0 < account1 <= self.size or not 0 < account2 <= self.size or (
                    self.balance[account1-1] < money
                ):
                    return False
                self.balance[account2-1] += money
                self.balance[account1-1] -= money
                return True
        
            def deposit(self, account: int, money: int) -> bool:
                if not 0 < account <= self.size:
                    return False
                self.balance[account-1] += money
                return True
        
            def withdraw(self, account: int, money: int) -> bool:
                if not 0 < account <= self.size or self.balance[account-1] < money:
                    return False
                self.balance[account-1] -= money
                return True
        
        
        # Your Bank object will be instantiated and called as such:
        # obj = Bank(balance)
        # param_1 = obj.transfer(account1,account2,money)
        # param_2 = obj.deposit(account,money)
        # param_3 = obj.withdraw(account,money)
        

        4.7.1226 - 2023-09-16 11:25:54 +0300 MSK

        Path With Minimum Effort

        Code

        class Solution:
        
            def minimumEffortPath(self, heights: List[List[int]]) -> int:
                rows, cols = len(heights), len(heights[0])
                directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
                dist = [[math.inf for _ in range(cols)] for _ in range(rows)]
                dist[0][0] = 0
                minHeap = [(0, 0, 0)] 
                while minHeap:
                    effort, x, y = heappop(minHeap)
                    if x == rows - 1 and y == cols - 1:
                        return effort
                    for dx, dy in directions:
                        nx, ny = x + dx, y + dy
                        if 0 <= nx < rows and 0 <= ny < cols:
                            new_effort = max(effort, abs(heights[x][y] - heights[nx][ny]))
                            if new_effort < dist[nx][ny]:
                                dist[nx][ny] = new_effort
                                heappush(minHeap, (new_effort, nx, ny))
        

        4.7.1227 - 2023-09-15 19:59:56 +0300 MSK

        Design a Number Container System

        Code

        class NumberContainers:
        
            def __init__(self):
                self.num_indices = defaultdict(list)
                self.num_at_index = {}
                
        
            def change(self, index: int, number: int) -> None:
                self.num_at_index[index] = number
                heapq.heappush(self.num_indices[number], index)
                
        
            def find(self, number: int) -> int:
                while self.num_indices[number] and self.num_at_index[self.num_indices[number][0]] != number:
                    heapq.heappop(self.num_indices[number])
                
                return self.num_indices[number][0] if len(self.num_indices[number]) > 0 else -1
                
        
        
        # Your NumberContainers object will be instantiated and called as such:
        # obj = NumberContainers()
        # obj.change(index,number)
        # param_2 = obj.find(number)
        

        4.7.1228 - 2023-09-15 19:53:02 +0300 MSK

        Design a Number Container System

        Code

        import sortedcontainers
        
        class NumberContainers:
        
            def __init__(self):
                self._idx_number = {}
                self._number_idx = defaultdict(sortedcontainers.SortedSet)
        
            def change(self, index: int, number: int) -> None:
                cur_number = self._idx_number.get(index, -1)
                if cur_number != -1:
                    self._number_idx[cur_number].remove(index)
                self._idx_number[index] = number
                self._number_idx[number].add(index)
        
            def find(self, number: int) -> int:
                ids = self._number_idx[number]
                return ids[0] if ids else -1
        
        
        # Your NumberContainers object will be instantiated and called as such:
        # obj = NumberContainers()
        # obj.change(index,number)
        # param_2 = obj.find(number)
        

        4.7.1229 - 2023-09-15 19:34:44 +0300 MSK

        Finding Pairs With a Certain Sum

        Code

        class FindSumPairs:
        
            def __init__(self, nums1: List[int], nums2: List[int]):
                self._nums1, self._nums2, self._nums2_raw = Counter(nums1), Counter(nums2), nums2
        
            def add(self, index: int, val: int) -> None:
                nums2_raw, nums2 = self._nums2_raw, self._nums2
                cur_val = nums2_raw[index]
                new_val = cur_val + val
                if nums2[cur_val] > 0:
                    nums2[cur_val] -= 1
                
                nums2_raw[index] = new_val
                nums2[new_val] += 1
        
            def count(self, tot: int) -> int:       
                return sum(num1_count * self._nums2.get(tot - num1, 0) 
                           for num1, num1_count in self._nums1.items())
        
        
        # Your FindSumPairs object will be instantiated and called as such:
        # obj = FindSumPairs(nums1, nums2)
        # obj.add(index,val)
        # param_2 = obj.count(tot)
        

        4.7.1230 - 2023-09-15 19:33:23 +0300 MSK

        Finding Pairs With a Certain Sum

        Code

        class FindSumPairs:
        
            def __init__(self, nums1: List[int], nums2: List[int]):
                self._nums1, self._nums2, self._nums2_raw = Counter(nums1), Counter(nums2), nums2
        
            def add(self, index: int, val: int) -> None:
                nums2_raw, nums2 = self._nums2_raw, self._nums2
                cur_val = nums2_raw[index]
                new_val = cur_val + val
                if nums2[cur_val] > 0:
                    nums2[cur_val] -= 1
                
                nums2_raw[index] = new_val
                nums2[new_val] += 1
        
            def count(self, tot: int) -> int:
                sum_count = 0
                nums2 = self._nums2
                for num1, num1_count in self._nums1.items():
                    sum_count += num1_count * nums2.get(tot - num1, 0) 
        
                return sum_count
        
        
        # Your FindSumPairs object will be instantiated and called as such:
        # obj = FindSumPairs(nums1, nums2)
        # obj.add(index,val)
        # param_2 = obj.count(tot)
        

        4.7.1231 - 2023-09-15 19:12:52 +0300 MSK

        Design Browser History

        Code

        class BrowserHistory:
        
            def __init__(self, homepage: str):
                self._history = [homepage]
                self._cur = 0
        
            def visit(self, url: str) -> None:
                self._history[self._cur+1:] = (url, )
                self._cur += 1
        
            def back(self, steps: int) -> str:
                self._cur = max(0, self._cur - steps)
                return self._history[self._cur]
        
            def forward(self, steps: int) -> str:
                self._cur = min(len(self._history) - 1, self._cur + steps)
                return self._history[self._cur]
        
        
        # Your BrowserHistory object will be instantiated and called as such:
        # obj = BrowserHistory(homepage)
        # obj.visit(url)
        # param_2 = obj.back(steps)
        # param_3 = obj.forward(steps)
        

        4.7.1232 - 2023-09-15 19:05:16 +0300 MSK

        Design a Stack With Increment Operation

        Code

        class CustomStack:
        
            def __init__(self, maxSize: int):
                self._stack = []
                self._max_size = maxSize
        
            def push(self, x: int) -> None:
                if len(self._stack) != self._max_size:
                    self._stack.append(x)
        
            def pop(self) -> int:
                return self._stack.pop() if self._stack else -1 
                
            def increment(self, k: int, val: int) -> None:
                for i in range(min(k, len(self._stack))):
                    self._stack[i] += val
        
        
        # Your CustomStack object will be instantiated and called as such:
        # obj = CustomStack(maxSize)
        # obj.push(x)
        # param_2 = obj.pop()
        # obj.increment(k,val)
        

        4.7.1233 - 2023-09-15 19:02:42 +0300 MSK

        Design a Stack With Increment Operation

        Code

        class CustomStack:
        
            def __init__(self, maxSize: int):
                self._stack = []
                self._max_size = maxSize
                self._size = 0
        
            def push(self, x: int) -> None:
                if self._size == self._max_size:
                    return
                self._stack.append(x)
                self._size += 1
        
            def pop(self) -> int:
                if self._size == 0:
                    return -1
                last = self._stack.pop()
                self._size -= 1
                return last
        
            def increment(self, k: int, val: int) -> None:
                for i in range(min(k, self._size)):
                    self._stack[i] += val
        
        
        # Your CustomStack object will be instantiated and called as such:
        # obj = CustomStack(maxSize)
        # obj.push(x)
        # param_2 = obj.pop()
        # obj.increment(k,val)
        

        4.7.1234 - 2023-09-15 18:53:00 +0300 MSK

        Design Linked List

        Code

        class Node:
            def __init__(self, val: int = 0, prev_node: 'Node' = None, next_node: 'Node' = None):
                self.val, self.prev, self.next = val, prev_node, next_node
        
        class MyLinkedList:
        
            def __init__(self):
                self._head, self._tail = Node(float("-inf")), Node(float("inf"))
                self._head.next, self._tail.prev = self._tail, self._head
                self._length = 0
        
            def _getNode(self, index: int) -> Node:
                if not 0 <= index < self._length:
                    return None
                if index == 0:
                    return self._head.next
                if index == self._length - 1:
                    return self._tail.prev
        
                cur_idx, cur_node = 0, self._head.next
                while cur_idx < index:
                    cur_node = cur_node.next
                    cur_idx += 1
        
                return cur_node
            
            def get(self, index: int) -> int:
                node = self._getNode(index)
                return node.val if node else -1
        
            def addAtHead(self, val: int) -> None:
                old_first = self._head.next
                new_node = Node(val, self._head, old_first)
                self._head.next, old_first.prev = new_node, new_node
                self._length += 1
        
            def addAtTail(self, val: int) -> None:
                old_tail = self._tail.prev
                new_node = Node(val, old_tail, self._tail)
                self._tail.prev, old_tail.next = new_node, new_node
                self._length += 1
        
            def addAtIndex(self, index: int, val: int) -> None:
                if not 0 <= index <= self._length:
                    return
                if index == 0:
                    self.addAtHead(val)
                    return
                if index == self._length:
                    self.addAtTail(val)
                    return
                
                target_node = self._getNode(index)
                prev_node = target_node.prev
                new_node = Node(val, prev_node, target_node)
                prev_node.next, target_node.prev = new_node, new_node
                self._length += 1
        
            def deleteAtIndex(self, index: int) -> None:
                if not 0 <= index < self._length:
                    return
                
                target_node = self._getNode(index)
                old_prev, old_next = target_node.prev, target_node.next
                old_prev.next, old_next.prev = old_next, old_prev
                self._length -= 1
        
        # Your MyLinkedList object will be instantiated and called as such:
        # obj = MyLinkedList()
        # param_1 = obj.get(index)
        # obj.addAtHead(val)
        # obj.addAtTail(val)
        # obj.addAtIndex(index,val)
        # obj.deleteAtIndex(index)
        

        4.7.1235 - 2023-09-15 17:07:59 +0300 MSK

        Range Sum Query 2D - Immutable

        Code

        class NumMatrix:
        
            def __init__(self, matrix: List[List[int]]):
                self.dp=[[0] * (len(matrix[0])+1) for _ in range(len(matrix)+1)]
                
        		# calculate prefix sum
                for r in range(len(self.dp)-1):
                    for c in range(len(self.dp[0])-1):
                        self.dp[r+1][c+1]=matrix[r][c] + self.dp[r][c+1] + self.dp[r+1][c] - self.dp[r][c]
                
            def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
                return self.dp[row2+1][col2+1] - self.dp[row1][col2+1] - self.dp[row2+1][col1] + self.dp[row1][col1]
                        
        

        4.7.1236 - 2023-09-15 12:51:11 +0300 MSK

        Peeking Iterator

        Code

        # Below is the interface for Iterator, which is already defined for you.
        #
        # class Iterator:
        #     def __init__(self, nums):
        #         """
        #         Initializes an iterator object to the beginning of a list.
        #         :type nums: List[int]
        #         """
        #
        #     def hasNext(self):
        #         """
        #         Returns true if the iteration has more elements.
        #         :rtype: bool
        #         """
        #
        #     def next(self):
        #         """
        #         Returns the next element in the iteration.
        #         :rtype: int
        #         """
        
        class PeekingIterator:
            def __init__(self, iterator):
                """
                Initialize your data structure here.
                :type iterator: Iterator
                """
                self._iter = iterator
                self._next = iterator.next()
                
        
            def peek(self):
                """
                Returns the next element in the iteration without advancing the iterator.
                :rtype: int
                """
                return self._next
                
        
            def next(self):
                """
                :rtype: int
                """
                cur_next = self._next
                self._next = self._iter.next() if self._iter.hasNext() else None
                return cur_next
                
        
            def hasNext(self):
                """
                :rtype: bool
                """
                return self._next is not None
                
        
        # Your PeekingIterator object will be instantiated and called as such:
        # iter = PeekingIterator(Iterator(nums))
        # while iter.hasNext():
        #     val = iter.peek()   # Get the next element but not advance the iterator.
        #     iter.next()         # Should return the same value as [val].
        

        4.7.1237 - 2023-09-15 09:59:15 +0300 MSK

        Min Cost to Connect All Points

        Code

        def manhattan_distance(p1: List[int], p2: List[int]) -> int:
            return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
        
        class Solution:
            def minCostConnectPoints(self, points: List[List[int]]) -> int:
                n = len(points)
                visited = [False] * n
                heap_dict = {0: 0}  
                min_heap = [(0, 0)]
                
                mst_weight = 0
                
                while min_heap:
                    w, u = heappop(min_heap)
                    
                    if visited[u] or heap_dict.get(u, float('inf')) < w:
                        continue
                    
                    visited[u] = True
                    mst_weight += w
                    
                    for v in range(n):
                        if not visited[v]:
                            new_distance = manhattan_distance(points[u], points[v])
              
                            if new_distance < heap_dict.get(v, float('inf')):
                                heap_dict[v] = new_distance
                                heappush(min_heap, (new_distance, v))
                
                return mst_weight
        

        4.7.1238 - 2023-09-14 19:02:15 +0300 MSK

        Frequency Tracker

        Code

        class FrequencyTracker:
        
            def __init__(self):
                self._num_freq = defaultdict(int)
                self._freq_nums = defaultdict(set)    
        
            def add(self, number: int) -> None:
                cur_freq = self._num_freq[number]
                self._num_freq[number] = cur_freq + 1
                self._freq_nums[cur_freq].discard(number)
                self._freq_nums[cur_freq + 1].add(number)
        
            def deleteOne(self, number: int) -> None:
                cur_freq = self._num_freq[number]
                if cur_freq == 0:
                    return    
                self._num_freq[number] = cur_freq - 1 
                self._freq_nums[cur_freq].discard(number)
                if cur_freq != 1:
                    self._freq_nums[cur_freq - 1].add(number)
        
            def hasFrequency(self, frequency: int) -> bool:
                return len(self._freq_nums[frequency]) != 0
        
        
        # Your FrequencyTracker object will be instantiated and called as such:
        # obj = FrequencyTracker()
        # obj.add(number)
        # obj.deleteOne(number)
        # param_3 = obj.hasFrequency(frequency)
        

        4.7.1239 - 2023-09-14 18:45:02 +0300 MSK

        Design an ATM Machine

        Code

        class ATM:
        
            def __init__(self):
                self._banknotes = (0, ) * 5
                self._values = (20, 50, 100, 200, 500)
        
            def deposit(self, banknotesCount: List[int]) -> None:
                self._banknotes = tuple(banknotesCount[i] + self._banknotes[i] for i in range(5))
        
            def withdraw(self, amount: int) -> List[int]:
                withdrawn = [0] * 5
                for i in reversed(range(5)):
                    value, notes_left = self._values[i], self._banknotes[i]
                    notes_need = min(notes_left, amount // value)
                    
                    if notes_need == 0:
                        continue
                    
                    amount -= value * notes_need
                    withdrawn[i] = notes_need
        
                    if amount == 0:
                        self._banknotes = tuple(self._banknotes[i] - withdrawn[i] 
                                                for i in range(5))
                        return withdrawn
        
                return (-1, )
        
        
        # Your ATM object will be instantiated and called as such:
        # obj = ATM()
        # obj.deposit(banknotesCount)
        # param_2 = obj.withdraw(amount)
        

        4.7.1240 - 2023-09-14 18:44:27 +0300 MSK

        Design an ATM Machine

        Code

        class ATM:
        
            def __init__(self):
                self._banknotes = (0, ) * 5
                self._values = (20, 50, 100, 200, 500)
        
            def deposit(self, banknotesCount: List[int]) -> None:
                self._banknotes = tuple(banknotesCount[i] + self._banknotes[i] for i in range(5))
        
            def withdraw(self, amount: int) -> List[int]:
                withdrawn = [0] * 5
                for i in reversed(range(5)):
                    value, notes_left = self._values[i], self._banknotes[i]
                    notes_need = min(notes_left, amount // value)
                    
                    if notes_need == 0:
                        continue
                    
                    amount -= value * notes_need
                    withdrawn[i] = notes_need
        
                    if amount == 0:
                        self._banknotes = tuple(self._banknotes[i] - withdrawn[i] 
                                                for i in range(5))
                        return withdrawn
        
                return (-1, )
        
        
        # Your ATM object will be instantiated and called as such:
        # obj = ATM()
        # obj.deposit(banknotesCount)
        # param_2 = obj.withdraw(amount)
        

        4.7.1241 - 2023-09-14 18:40:55 +0300 MSK

        Design an ATM Machine

        Code

        class ATM:
        
            def __init__(self):
                self._banknotes = [0] * 5
                self._values = (20, 50, 100, 200, 500)
        
            def deposit(self, banknotesCount: List[int]) -> None:
                for i in range(5):
                    self._banknotes[i] += banknotesCount[i]
        
            def withdraw(self, amount: int) -> List[int]:
                withdrawn = [0] * 5
                for i in reversed(range(5)):
                    value, notes_left = self._values[i], self._banknotes[i]
                    notes_need = min(notes_left, amount // value)
                    
                    if notes_need == 0:
                        continue
                    
                    amount -= value * notes_need
                    withdrawn[i] = notes_need
        
                    if amount == 0:
                        for i in range(5):
                            self._banknotes[i] -= withdrawn[i]
                        return withdrawn
        
                return [-1]
        
        
        # Your ATM object will be instantiated and called as such:
        # obj = ATM()
        # obj.deposit(banknotesCount)
        # param_2 = obj.withdraw(amount)
        

        4.7.1242 - 2023-09-14 18:08:10 +0300 MSK

        Design Memory Allocator

        Code

        class Allocator:
        
            def __init__(self, n: int):
              self._units = [1] * n
              self._units[0] = n
              self._id_units = defaultdict(list)
              self._units_count = n
        
            def find_avail_units(self, start: int, size: int) -> Tuple[int, int]:
                i = start
                count = 0
                while i < self._units_count and i - start < size:
                    units_avail = self._units[i]
                    if units_avail < 0:
                        return i + units_avail if i == start else i, count
                    i += units_avail
                    count += units_avail
        
                return i, count
                    
        
            def allocate(self, size: int, mID: int) -> int:
                i = 0
                units_start, units_count = None, 0
                while i < self._units_count and units_count < size:
                    units_avail = self._units[i]
                    if units_avail < 0:
                        i += -units_avail
                        units_start, units_count = None, 0
                        continue
        
                    if units_start is None:
                        units_start = i
                    units_count += units_avail
                    i += units_avail
        
                if units_count < size:
                    return -1 
        
                self._units[units_start] = -size
                if units_count > size:
                    self._units[units_start + size] = units_count - size
                self._id_units[mID].append(units_start)
                return units_start
        
            def free(self, mID: int) -> int:
                count = 0
                conseq_units = self._id_units[mID]
                while conseq_units:
                    units_start = conseq_units.pop()
                    units_freed = -self._units[units_start]
                    count += units_freed
                    self._units[units_start] = units_freed
        
                return count
        
        
        # Your Allocator object will be instantiated and called as such:
        # obj = Allocator(n)
        # param_1 = obj.allocate(size,mID)
        # param_2 = obj.free(mID)
        

        4.7.1243 - 2023-09-14 14:41:43 +0300 MSK

        Reconstruct Itinerary

        Code

        class Solution:
            def findItinerary(self, tickets: List[List[str]]) -> List[str]:
                graph = defaultdict(list)
                
                for src, dst in sorted(tickets, reverse=True):
                    graph[src].append(dst)
                    
                itinerary = []
                def dfs(airport: str) -> None:
                    while graph[airport]:
                        dfs(graph[airport].pop())
                    
                    itinerary.append(airport)
                
                dfs("JFK")
                
                return itinerary[::-1]
        

        4.7.1244 - 2023-09-13 19:20:05 +0300 MSK

        Detect Squares

        Code

        class DetectSquares:
        
            def __init__(self):
                self._row_col = defaultdict(lambda: defaultdict(int))
        
            def add(self, point: List[int]) -> None:
                self._row_col[point[0]][point[1]] += 1
        
            def count(self, point: List[int]) -> int:
                ways_count = 0
                row1, col1 = point
                for col2, col2_count in self._row_col[row1].items():
                    if col2 == col1:
                        continue
        
                    side = col2 - col1
                    for row2 in (row1 + side, row1 - side):
                        point3_count = self._row_col[row2][col1]
                        point4_count = self._row_col[row2][col2]
                        ways_count += col2_count * point3_count * point4_count
        
                return ways_count
        
        # Your DetectSquares object will be instantiated and called as such:
        # obj = DetectSquares()
        # obj.add(point)
        # param_2 = obj.count(point)
        

        4.7.1245 - 2023-09-13 11:18:48 +0300 MSK

        Candy

        Code

        class Solution:
            def candy(self, ratings: List[int]) -> int:
                child_count = len(ratings)
                candies = [1] * child_count 
        
                for i in range(1, child_count):
                    if ratings[i] > ratings[i-1]:
                        candies[i] = candies[i-1] + 1
        
                for i in reversed(range(child_count - 1)):
                    if ratings[i] > ratings[i+1]:
                        candies[i] = max(candies[i], candies[i+1] + 1)
                
                return sum(candies)
        

        4.7.1246 - 2023-09-12 19:36:36 +0300 MSK

        Tweet Counts Per Frequency

        Code

        class TweetCounts:
        
            def __init__(self):
                self._tweets = defaultdict(list)
                self._chunk_ranges = {
                    "minute": 60, 
                    "hour": 3600, 
                    "day": 86400
                }
        
            def recordTweet(self, tweetName: str, time: int) -> None:
                self._tweets[tweetName].append(time)
        
            def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:
                chunk_range = self._chunk_ranges[freq]
                chunks = [0] * (1 + (endTime - startTime) // chunk_range)
        
                for tweet in self._tweets[tweetName]:
                    if not startTime <= tweet <= endTime:
                        continue
                    chunks[(tweet - startTime) // chunk_range] += 1
                
                return chunks
        
        
        
        
        # Your TweetCounts object will be instantiated and called as such:
        # obj = TweetCounts()
        # obj.recordTweet(tweetName,time)
        # param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime)
        

        4.7.1247 - 2023-09-12 16:32:10 +0300 MSK

        Snapshot Array

        Code

        class SnapshotArray:
        
            def __init__(self, length: int):
                self._cur_snap = 0
                self._elems = [[(0, 0)] for _ in range(length)]
        
            def set(self, index: int, val: int) -> None:
                values = self._elems[index]
                if values[-1][0] == self._cur_snap:
                    values.pop()
                values.append((self._cur_snap, val))
        
            def snap(self) -> int:
                self._cur_snap += 1
                return self._cur_snap - 1 
        
            def get(self, index: int, snap_id: int) -> int:
                for cur_snap_id, val in reversed(self._elems[index]):
                    if cur_snap_id > snap_id:
                        continue
                    return val
                
                return -1
                
        
        
        # Your SnapshotArray object will be instantiated and called as such:
        # obj = SnapshotArray(length)
        # obj.set(index,val)
        # param_2 = obj.snap()
        # param_3 = obj.get(index,snap_id)
        

        4.7.1248 - 2023-09-12 15:42:35 +0300 MSK

        Time Based Key-Value Store

        Code

        class TimeMap:
        
            def __init__(self):
                self._cache = defaultdict(list)
                
        
            def set(self, key: str, value: str, timestamp: int) -> None:
                self._cache[key].append((timestamp, value))
        
            def get(self, key: str, timestamp: int) -> str:
                for cur_timestamp, value in reversed(self._cache[key]):
                    if cur_timestamp > timestamp:
                        continue
                    return value
        
                return ""
        
        # Your TimeMap object will be instantiated and called as such:
        # obj = TimeMap()
        # obj.set(key,value,timestamp)
        # param_2 = obj.get(key,timestamp)
        

        4.7.1249 - 2023-09-12 15:27:56 +0300 MSK

        Design Parking System

        Code

        class ParkingSystem:
        
            def __init__(self, big: int, medium: int, small: int):
                self._slots = [0, big, medium, small]
        
            def addCar(self, carType: int) -> bool:
                slots_avail = self._slots[carType]
                if not slots_avail:
                    return False
                self._slots[carType] = slots_avail - 1
                return True
        
        
        # Your ParkingSystem object will be instantiated and called as such:
        # obj = ParkingSystem(big, medium, small)
        # param_1 = obj.addCar(carType)
        

        4.7.1250 - 2023-09-12 15:23:56 +0300 MSK

        Design Parking System

        Code

        class ParkingSystem:
        
            def __init__(self, big: int, medium: int, small: int):
                self._slots = [big, medium, small]
        
            def addCar(self, carType: int) -> bool:
                if self._slots[carType-1] == 0:
                    return False
                self._slots[carType-1] -= 1
                return True
        
        
        # Your ParkingSystem object will be instantiated and called as such:
        # obj = ParkingSystem(big, medium, small)
        # param_1 = obj.addCar(carType)
        

        4.7.1251 - 2023-09-12 15:21:06 +0300 MSK

        Number of Recent Calls

        Code

        class RecentCounter:
        
            def __init__(self):
                self._queue = deque()
        
            def ping(self, t: int) -> int:
                self._queue.append(t)
                while self._queue:
                    if t - self._queue[0] > 3000:
                        self._queue.popleft()
                    else:
                        break
        
                return len(self._queue) 
        
        
        # Your RecentCounter object will be instantiated and called as such:
        # obj = RecentCounter()
        # param_1 = obj.ping(t)
        

        4.7.1252 - 2023-09-12 14:23:58 +0300 MSK

        Range Sum Query - Immutable

        Code

        class NumArray:
        
            def __init__(self, nums: List[int]):
                self._sums = tuple(accumulate(nums))
        
            def sumRange(self, left: int, right: int) -> int:
                # [-2, 0, 3, -5, 2, -1], [-2, -2, 1, -4, -2, -3]
                # [0, 2] -> 1
                if left == 0:
                    return self._sums[right]
        
                return self._sums[right] - self._sums[left-1]
        
        
        # Your NumArray object will be instantiated and called as such:
        # obj = NumArray(nums)
        # param_1 = obj.sumRange(left,right)
        

        4.7.1253 - 2023-09-12 14:12:53 +0300 MSK

        Range Sum Query - Immutable

        Code

        class NumArray:
        
            def __init__(self, nums: List[int]):
                self._nums = nums
        
            @cache
            def sumRange(self, left: int, right: int) -> int:
                if right == left:
                    return self._nums[left]
                if right - left == 1:
                    return self._nums[right] + self._nums[left]
                mid = left + (right - left) // 2
                return self.sumRange(left, mid) + self.sumRange(mid + 1, right)
        
        
        # Your NumArray object will be instantiated and called as such:
        # obj = NumArray(nums)
        # param_1 = obj.sumRange(left,right)
        

        4.7.1254 - 2023-09-12 14:07:17 +0300 MSK

        Range Sum Query - Immutable

        Code

        class NumArray:
        
            def __init__(self, nums: List[int]):
                self._nums = nums
        
            def sumRange(self, left: int, right: int) -> int:
                return sum(self._nums[left:right+1])
        
        
        # Your NumArray object will be instantiated and called as such:
        # obj = NumArray(nums)
        # param_1 = obj.sumRange(left,right)
        

        4.7.1255 - 2023-09-12 14:05:44 +0300 MSK

        Binary Search Tree Iterator

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class BSTIterator:
        
            def __init__(self, root: Optional[TreeNode]):
                def generate(node: TreeNode) -> int:
                    if not node:
                        return
                    yield from generate(node.left)
                    yield node
                    yield from generate(node.right)
        
                self._generate = generate(root)
                self._next = next(self._generate)
        
            def next(self) -> int:
                next_val = self._next.val
                self._next = next(self._generate, None)
                return next_val 
        
            def hasNext(self) -> bool:
                return self._next is not None
        
        
        # Your BSTIterator object will be instantiated and called as such:
        # obj = BSTIterator(root)
        # param_1 = obj.next()
        # param_2 = obj.hasNext()
        

        4.7.1256 - 2023-09-12 14:05:12 +0300 MSK

        Binary Search Tree Iterator

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class BSTIterator:
        
            def __init__(self, root: Optional[TreeNode]):
                def generate(node: TreeNode) -> int:
                    if not node:
                        return
                    yield from generate(node.left)
                    yield node
                    yield from generate(node.right)
        
                self._generate = generate(root)
                self._next = next(self._generate)
        
            def next(self) -> int:
                next_val = self._next.val
                self._next = next(self._generate, None)
                return next_val 
        
            def hasNext(self) -> bool:
                return not self._next is None
        
        
        # Your BSTIterator object will be instantiated and called as such:
        # obj = BSTIterator(root)
        # param_1 = obj.next()
        # param_2 = obj.hasNext()
        

        4.7.1257 - 2023-09-12 14:01:45 +0300 MSK

        Binary Search Tree Iterator

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class BSTIterator:
        
            def __init__(self, root: Optional[TreeNode]):
                self._stack = []
                while root:
                    self._stack.append(root)
                    root = root.left
        
            def next(self) -> int:
                node = self._stack.pop()
                right = node.right
                while right:
                    self._stack.append(right)
                    right = right.left
                
                return node.val
        
            def hasNext(self) -> bool:
                return self._stack
        
        
        # Your BSTIterator object will be instantiated and called as such:
        # obj = BSTIterator(root)
        # param_1 = obj.next()
        # param_2 = obj.hasNext()
        

        4.7.1258 - 2023-09-12 11:17:46 +0300 MSK

        Balanced Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def isBalanced(self, root: Optional[TreeNode]) -> bool:
                def get_height(node: TreeNode) -> int:
                    if not node:
                        return 0
                    
                    h_left = get_height(node.left)
                    if h_left < 0:
                        return -1
                    h_right = get_height(node.right)
                    if h_right < 0 or abs(h_left - h_right) > 1:
                        return -1
        
                    return max(h_left, h_right) + 1
                
                return get_height(root) >= 0
        

        4.7.1259 - 2023-09-12 10:55:04 +0300 MSK

        Minimum Deletions to Make Character Frequencies Unique

        Code

        class Solution:
            def minDeletions(self, s: str) -> int:
                length = len(s)
                char_count = Counter(s)
                counts = set()
                deleted_chars = 0
        
                for char, count in char_count.items():
                    while count != 0 and count in counts:
                        count -= 1
                        deleted_chars += 1
                    if count != 0:
                        counts.add(count)
                    
                return deleted_chars
        

        4.7.1260 - 2023-09-11 19:32:16 +0300 MSK

        Intersection of Two Linked Lists

        Code

        class Solution:
            def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
                if not headA or not headB:
                    return None
                
                tail1, tail2 = headA, headB
                while tail1 != tail2:
                    tail1 = tail1.next if tail1 else headB
                    tail2 = tail2.next if tail2 else headA
                
                return tail2
            
        

        4.7.1261 - 2023-09-11 19:31:11 +0300 MSK

        Intersection of Two Linked Lists

        Code

        class Solution:
            def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
                if headA and headB:
                    A, B = headA, headB
                    while A != B:
                        A = A.next if A else headB
                        B = B.next if B else headA
                    return B
                
        

        4.7.1262 - 2023-09-11 19:16:39 +0300 MSK

        Pascal’s Triangle II

        Code

        class Solution:
            def getRow(self, rowIndex: int) -> List[int]:
                prev_row = (1,)
                
                for i in range(1, rowIndex + 1):
                    prev_row = (1, *(prev_row[j] + prev_row[j+1] for j in range(len(prev_row) - 1)), 1)
                
                return prev_row
        

        4.7.1263 - 2023-09-11 19:06:00 +0300 MSK

        Single Number

        Code

        class Solution:
            def singleNumber(self, nums: List[int]) -> int:
                return reduce(xor, nums)
        

        4.7.1264 - 2023-09-11 18:58:15 +0300 MSK

        Single Number

        Code

        class Solution:
            def singleNumber(self, nums: List[int]) -> int:
                return reduce(lambda total, element: total ^ element, nums)
        

        4.7.1265 - 2023-09-11 18:55:49 +0300 MSK

        Single Number

        Code

        class Solution:
            def singleNumber(self, nums: List[int]) -> int:
                nums_count = len(nums)
                if nums_count == 1:
                    return nums[0]
                
                nums.sort()
                for i in range(0, nums_count, 2):
                    if i + 1 == nums_count:
                        return nums[i]
        
                    cur_num, next_num = nums[i], nums[i+1]
                    if cur_num == next_num:
                        continue
                    
                    return cur_num
                
                return 0
        

        4.7.1266 - 2023-09-11 18:46:11 +0300 MSK

        Minimum Depth of Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def minDepth(self, root: Optional[TreeNode]) -> int:
                
                def dfs(node: TreeNode) -> int:
                    if not node:
                        return 0
        
                    return 1 + min((depth for depth in (dfs(node.left), dfs(node.right)) if depth > 0),
                                   default=0)
        
                return dfs(root)
        

        4.7.1267 - 2023-09-11 18:31:16 +0300 MSK

        Binary Tree Inorder Traversal

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
                def get_nodes(root: TreeNode) -> Generator[None, None, TreeNode]:
                    if not root:
                        return
        
                    yield from get_nodes(root.left)
                    yield root.val
                    yield from get_nodes(root.right)
                
                return tuple(get_nodes(root))
        

        4.7.1268 - 2023-09-11 18:30:56 +0300 MSK

        Binary Tree Inorder Traversal

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
                def get_nodes(root: TreeNode) -> Generator[None, None, TreeNode]:
                    if not root:
                        return
        
                    if root.left:
                        yield from get_nodes(root.left)
                    
                    yield root.val
        
                    if root.right:
                        yield from get_nodes(root.right)
                
                return tuple(get_nodes(root))
        

        4.7.1269 - 2023-09-11 15:06:55 +0300 MSK

        Group the People Given the Group Size They Belong To

        Code

        class Solution:
            def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
                answer = []
                cur_groups = defaultdict(list)
                
                for i in range(len(groupSizes)):
                    size = groupSizes[i]
                    group = cur_groups[size]
                    group.append(i)
                    if len(group) == size:
                        answer.append(group)
                        del cur_groups[size]
                
                return answer
        

        4.7.1270 - 2023-09-10 12:48:15 +0300 MSK

        Count All Valid Pickup and Delivery Options

        Code

        class Solution:
            def countOrders(self, n: int) -> int:
                # P1, D1                 [01] -> (P1, D1)
                # P1, D1, P2, D2         [06] -> (P1, P2, D1, D2), (P1, P2, D2, D1), 
                #                                (P1, D1, P2, D2), (P2, P1, D1, D2), 
                #                                (P2, P1, D2, D1), (P2, D2, P1, D1).
                # P1, D1, P2, D2, P3, D3 [90]
                
                ways_count = 1
                mod = 10**9 + 7
                for order in range(2, n + 1):
                    pos_avail_count = 1 + (order - 1) * 2
                    cur_ways_count = pos_avail_count * (pos_avail_count + 1) // 2
                    ways_count = (ways_count * cur_ways_count) % mod
        
                return ways_count
        

        4.7.1271 - 2023-09-10 12:37:39 +0300 MSK

        Count All Valid Pickup and Delivery Options

        Code

        class Solution:
            def countOrders(self, n: int) -> int:
                # P1, D1                 [01] -> (P1, D1)
                # P1, D1, P2, D2         [06] -> (P1, P2, D1, D2), (P1, P2, D2, D1), 
                #                                (P1, D1, P2, D2), (P2, P1, D1, D2), 
                #                                (P2, P1, D2, D1), (P2, D2, P1, D1).
                # P1, D1, P2, D2, P3, D3 [90]
                
                ways_count = 1
                for order in range(2, n + 1):
                    avail_pos_count = 1 + (order - 1) * 2
                    ways_count *= sum(avail_pos_count - pos for pos in range(avail_pos_count))
        
                return ways_count % (10**9 + 7)
        

        4.7.1272 - 2023-09-09 20:12:03 +0300 MSK

        Decode Ways

        Code

        class Solution:
            def numDecodings(self, s: str) -> int:
                char_count = len(s)
        
                @cache
                def dfs(i: int) -> int:
                    if i == char_count: 
                        return 1
                    if s[i] == "0": 
                        return 0
                    return dfs(i + 1) + (
                        dfs(i + 2) if i + 1 < char_count and s[i:i+2] < "27" else 0
                    )
        
                return dfs(0)
        

        4.7.1273 - 2023-09-09 20:11:23 +0300 MSK

        Decode Ways

        Code

        class Solution:
            def numDecodings(self, s: str) -> int:
                char_count = len(s)
        
                @cache
                def dfs(i: int) -> int:
                    if i == char_count: 
                        return 1
                    if s[i] == "0": 
                        return 0
                    return dfs(i + 1) + (dfs(i + 2) if i + 1 < char_count and s[i:i+2] < "27" else 0)
        
                return dfs(0)
        

        4.7.1274 - 2023-09-09 20:10:19 +0300 MSK

        Decode Ways

        Code

        class Solution:
            def numDecodings(self, s: str) -> int:
                char_count = len(s)
        
                @cache
                def dfs(i: int) -> int:
                    if i == char_count: 
                        return 1
                    if s[i] == "0": 
                        return 0
                    ways_count = dfs(i + 1)
                    if i + 1 < char_count and s[i:i+2] < "27":
                        ways_count += dfs(i + 2)
                    return ways_count
        
                return dfs(0)
        

        4.7.1275 - 2023-09-09 16:06:56 +0300 MSK

        Snakes and Ladders

        Code

        class Solution:
            def snakesAndLadders(self, board: List[List[int]]) -> int:
                n = len(board)
                board.reverse()
        
                def intToPos(square):
                    r = (square - 1) // n
                    c = (square - 1) % n
                    if r % 2:
                        c = n - 1 - c
                    return [r, c]
        
                q = deque()
                q.append([1, 0]) 
                visit = set()
                while q:
                    square, moves = q.popleft()
                    for i in range(1, 7):
                        nextSquare = square + i
                        r, c = intToPos(nextSquare)
                        if board[r][c] != -1:
                            nextSquare = board[r][c]
                        if nextSquare == n * n:
                            return moves + 1
                        if nextSquare not in visit:
                            visit.add(nextSquare)
                            q.append([nextSquare, moves + 1])
                return -1
        

        4.7.1276 - 2023-09-09 10:20:58 +0300 MSK

        Combination Sum IV

        Code

        class Solution:
            def combinationSum4(self, nums: List[int], target: int) -> int:
        
                @cache
                def dp(cur_sum: int) -> int:
                    if cur_sum == target:
                        return 1
                    if cur_sum > target:
                        return 0
                    
                    return sum(dp(cur_sum + num) for num in nums)
        
                return dp(0)
                    
        

        4.7.1277 - 2023-09-09 10:20:26 +0300 MSK

        Combination Sum IV

        Code

        class Solution:
            def combinationSum4(self, nums: List[int], target: int) -> int:
        
                @cache
                def backtrack(cur_sum: int) -> int:
                    if cur_sum == target:
                        return 1
                    if cur_sum > target:
                        return 0
                    
                    return sum(backtrack(cur_sum + num) for num in nums)
        
                return backtrack(0)
                    
        

        4.7.1278 - 2023-09-08 13:41:10 +0300 MSK

        Pascal’s Triangle

        Code

        class Solution:
            def generate(self, numRows: int) -> List[List[int]]:
                answer = [[1]]
                numRows -= 1
        
                while numRows > 0:
                    cur, prev = [1], answer[-1]
                    for i in range(len(prev) - 1):
                        cur.append(prev[i] + prev[i+1])
                    cur.append(1)
                    answer.append(cur)
                    numRows -= 1
                
                return answer
        

        4.7.1279 - 2023-09-07 20:09:04 +0300 MSK

        Word Search

        Code

        class Solution:
            def exist(self, board: List[List[str]], word: str) -> bool:
                row_count, col_count = len(board), len(board[0])
                word_length = len(word)
                delta = ((0, 1), (0, -1), (1, 0), (-1, 0))
        
                if word_length == 1:
                    return any(word in row for row in board)
                if word_length > row_count * col_count:
                    return False
        
                visited = set()
        
                def backtrack(row: int, col: int, target: int) -> bool:
                    if target == word_length:
                        return True
                    if not 0 <= row < row_count or not 0 <= col < col_count or (
                        (row, col) in visited or board[row][col] != word[target]
                    ):
                        return False
        
                    visited.add((row, col))
                    answer = any(backtrack(row + delta_row, col + delta_col, target + 1)
                                 for delta_row, delta_col in delta)
                    visited.remove((row, col))
                    return answer
        
                return any(backtrack(row, col, 0) 
                           for row in range(row_count) 
                           for col in range(col_count))
        

        4.7.1280 - 2023-09-07 20:00:09 +0300 MSK

        Word Search

        Code

        class Solution:
            def exist(self, board: List[List[str]], word: str) -> bool:
                row_count, col_count = len(board), len(board[0])
                word_length = len(word)
                delta = ((0, 1), (0, -1), (1, 0), (-1, 0))
        
                if word_length == 1:
                    return any(word in row for row in board)
        
                def backtrack(row: int, col: int, visited: Set, target: int) -> bool:
                    if (row, col) in visited or not 0 <= row < row_count or not 0 <= col < col_count:
                        return False
        
                    if board[row][col] != word[target]:
                        return False
                    
                    if target == word_length - 1:
                        return True
        
                    visited.add((row, col))
                    if any(backtrack(row + delta_row, col + delta_col, visited, target + 1)
                           for delta_row, delta_col in delta):
                        return True
                    visited.remove((row, col))
                    return False
                
                start_char = word[0]
        
                return any(backtrack(row, col, set(), 0) 
                           for row in range(row_count) 
                           for col in range(col_count)
                           if board[row][col] == start_char)
        

        4.7.1281 - 2023-09-07 19:55:32 +0300 MSK

        Word Search

        Code

        class Solution:
            def exist(self, board: List[List[str]], word: str) -> bool:
                row_count, col_count = len(board), len(board[0])
                word_length = len(word)
                delta = ((0, 1), (0, -1), (1, 0), (-1, 0))
        
                if word_length == 1:
                    return any(word in row for row in board)
        
                def backtrack(row: int, col: int, visited: Set, target: int) -> bool:
                    if (row, col) in visited or not 0 <= row < row_count or not 0 <= col < col_count:
                        return False
        
                    if board[row][col] != word[target]:
                        return False
                    
                    if target == word_length - 1:
                        return True
        
                    visited.add((row, col))
                    if any(backtrack(row + delta_row, col + delta_col, visited, target + 1)
                           for delta_row, delta_col in delta):
                        return True
                    visited.remove((row, col))
                    return False
                
                for row in range(row_count):
                    for col in range(col_count):
                        if backtrack(row, col, set(), 0):
                            return True
                
                return False
        

        4.7.1282 - 2023-09-07 17:13:51 +0300 MSK

        Reverse Linked List II

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
                cur_node = 1
                left_head, left_tail = head if left > 1 else None, None
        
                while cur_node < left:
                    cur_node += 1
                    head, left_tail = head.next, head
        
                cur_node += 1
                mid_head, mid_tail, head = head, head, head.next
                mid_head.next = None
        
                while cur_node <= right:
                    cur_node += 1
                    mid_head, head.next, head = head, mid_head, head.next
            
                mid_tail.next = head
                if left_head:
                    left_tail.next = mid_head
                else:
                    left_head = mid_head
        
                return left_head
        

        4.7.1283 - 2023-09-07 17:13:34 +0300 MSK

        Reverse Linked List II

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
                cur_node = 1
                left_head, left_tail = head if left > 1 else None, None
        
                while cur_node < left:
                    cur_node += 1
                    head, left_tail = head.next, head
        
                cur_node += 1
                mid_head, mid_tail, head = head, head, head.next
                mid_head.next = None
        
                while cur_node <= right:
                    cur_node += 1
                    next_node = head.next
                    mid_head, head.next = head, mid_head
                    head = next_node
            
                mid_tail.next = head
                if left_head:
                    left_tail.next = mid_head
                else:
                    left_head = mid_head
        
                return left_head
        

        4.7.1284 - 2023-09-07 17:12:50 +0300 MSK

        Reverse Linked List II

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
                cur_node = 1
                left_head, left_tail = head if left > 1 else None, None
        
                while cur_node < left:
                    cur_node += 1
                    head, left_tail = head.next, head
        
                cur_node += 1
                mid_head, mid_tail, head = head, head, head.next
                mid_head.next = None
        
                while cur_node <= right:
                    cur_node += 1
                    next_node = head.next
                    head.next = mid_head
                    mid_head = head
                    head = next_node
            
                mid_tail.next = head
                if left_head:
                    left_tail.next = mid_head
                else:
                    left_head = mid_head
        
                return left_head
        

        4.7.1285 - 2023-09-06 14:59:03 +0300 MSK

        Split Linked List in Parts

        Code

        class Solution:
            def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:        
                nodes_count = 0
                tail = head
                while tail:
                    tail = tail.next
                    nodes_count += 1
                
                quotient, remainder = divmod(nodes_count, k)
                answer = []
                for i in range(k):
                    size = quotient + 1 if (remainder := remainder - 1) >= 0 else quotient
        
                    answer.append(head)
                    last = None
                    while size > 0:
                        last = head
                        head = head.next
                        size -= 1
                    if last: 
                        last.next = None
                        
                return answer
        

        4.7.1286 - 2023-09-05 11:41:23 +0300 MSK

        Copy List with Random Pointer

        Code

        """
        # Definition for a Node.
        class Node:
            def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
                self.val = int(x)
                self.next = next
                self.random = random
        """
        
        class Solution:
            def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
                
                copied = {None: None}
        
                def copy_node(node: Node) -> Node:
                    if node in copied:
                        return copied[node]
                    
                    new_node = Node(node.val)
                    copied[node] = new_node
                    new_node.next = copy_node(node.next)
                    new_node.random = copy_node(node.random)
                    return new_node
                
                return copy_node(head)
        

        4.7.1287 - 2023-09-04 15:54:45 +0300 MSK

        Combination Sum

        Code

        class Solution:
            def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
                result = set()
                cur_nums = []
        
                def backtrack(cur_sum: int) -> None:
                    if cur_sum == target:
                        result.add(tuple(sorted(cur_nums[:])))
                    if cur_sum >= target:
                        return
        
                    for num in candidates:
                        cur_nums.append(num)
                        backtrack(num + cur_sum)
                        cur_nums.pop() 
        
                backtrack(0)
        
                return result
        

        4.7.1288 - 2023-09-04 12:44:01 +0300 MSK

        Convert Sorted Array to Binary Search Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
                nums_count = len(nums)
                if nums_count == 0:
                    return None
                
                mid = nums_count // 2
                return TreeNode(nums[mid], 
                                self.sortedArrayToBST(nums[:mid]), 
                                self.sortedArrayToBST(nums[mid+1:]))
        

        4.7.1289 - 2023-09-04 09:37:09 +0300 MSK

        Linked List Cycle

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, x):
        #         self.val = x
        #         self.next = None
        
        class Solution:
            def hasCycle(self, head: Optional[ListNode]) -> bool:
                slow_p, fast_p = head, head.next if head else None
                while fast_p and fast_p.next:
                    if slow_p == fast_p:
                        return True
                    slow_p, fast_p = slow_p.next, fast_p.next.next
        
                return False
        

        4.7.1290 - 2023-09-03 20:06:29 +0300 MSK

        Game of Life

        Code

        class Solution:
            def gameOfLife(self, board: List[List[int]]) -> None:
                """
                Do not return anything, modify board in-place instead.
                """
                rows_count, cols_count = len(board), len(board[0])
                moves = ((0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1))
                flip_cells = set()
                
                for row in range(rows_count):
                    for col in range(cols_count):
                        live_neighbors = 0
                        is_alive = board[row][col] == 1
        
                        for row_delta, col_delta in moves:
                            new_row, new_col = row + row_delta, col + col_delta
                            if not 0 <= new_row < rows_count or not 0 <= new_col < cols_count:
                                continue
                            if board[new_row][new_col] == 1:
                                live_neighbors += 1
        
                        if (is_alive and (live_neighbors < 2 or live_neighbors > 3)) or (
                            not is_alive and live_neighbors == 3
                        ):
                            flip_cells.add((row, col))
                
                while flip_cells:
                    row, col = flip_cells.pop()
                    board[row][col] = 0 if board[row][col] == 1 else 1
        

        4.7.1291 - 2023-09-03 19:49:38 +0300 MSK

        Set Matrix Zeroes

        Code

        class Solution:
            def setZeroes(self, matrix: List[List[int]]) -> None:
                """
                Do not return anything, modify matrix in-place instead.
                """
                rows_count, cols_count = len(matrix), len(matrix[0])
                flip_rows, flip_cols = set(), set()
        
                for row in range(rows_count):
                    for col in range(cols_count):
                        if matrix[row][col] == 0:
                            flip_rows.add(row)
                            flip_cols.add(col)
        
                while flip_rows:
                    row = flip_rows.pop()
                    for col in range(cols_count):
                        if matrix[row][col] != 0:
                            matrix[row][col] = 0
                
                while flip_cols:
                    col = flip_cols.pop()
                    for row in range(rows_count):
                        if matrix[row][col] != 0:
                            matrix[row][col] = 0
                
                    
        

        4.7.1292 - 2023-09-03 11:23:58 +0300 MSK

        Unique Paths

        Code

        class Solution:
            def uniquePaths(self, m: int, n: int) -> int:
        
                @cache
                def dp(row: int, col: int) -> int:
                    if not 0 <= row < m or not 0 <= col < n:
                        return 0
                    
                    if row == m - 1 and col == n - 1:
                        return 1
                    
                    return dp(row + 1, col) + dp(row, col + 1)
        
                return dp(0, 0)
        

        4.7.1293 - 2023-09-02 16:26:14 +0300 MSK

        Rotate Image

        Code

        class Solution:
            def rotate(self, matrix: List[List[int]]) -> None:
                """
                Do not return anything, modify matrix in-place instead.
                """
                side_length = len(matrix)
        
                for row in range(side_length // 2):
                    matrix[row], matrix[-row-1] = matrix[-row-1], matrix[row]
                
                for i in range(side_length):
                    for j in range(i):
                        matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
        

        4.7.1294 - 2023-09-02 10:50:42 +0300 MSK

        Extra Characters in a String

        Code

        class Solution:
            def minExtraChar(self, s: str, dictionary: List[str]) -> int:
                chars_count = len(s)
        
                @cache
                def dp(i: int) -> int:
                    chars_left = chars_count - i
                    if chars_left == 0:
                        return 0
                    
                    min_extra_chars = chars_left
        
                    for word in dictionary:
                        word_length = len(word)
        
                        if word_length > chars_left or s[i:i+word_length] != word:
                            continue
                        
                        if word_length == chars_left:
                            return 0
        
                        min_extra_chars = min(min_extra_chars, dp(i + word_length))
        
                    return min(min_extra_chars, 1 + dp(i + 1))
                
                return dp(0)
        
                        
        

        4.7.1295 - 2023-09-01 18:41:17 +0300 MSK

        Text Justification

        Code

        class Solution:
            def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
                words_count = len(words)
                
                def get_line(word_idx: int) -> Tuple[List[str], int]:
                    line = []
                    line_length = 0
        
                    for i in range(word_idx, words_count):
                        word = words[i]
                        word_length = len(word)
                        if line_length + word_length > maxWidth:
                            break
        
                        line.append(word)
                        line_length += word_length + 1 
        
                    return line, line_length
                
                def create_line(line: List[str], line_length: int, word_idx: int) -> str:
                    base_length = line_length - 1
                    extra_spaces = maxWidth - base_length
        
                    if len(line) == 1 or word_idx == words_count:
                        return " ".join(line) + " " * extra_spaces
        
                    word_count = len(line) - 1
                    spaces_per_word = extra_spaces // word_count
                    needs_extra_space = extra_spaces % word_count
        
                    for j in range(needs_extra_space):
                        line[j] += " "
        
                    for j in range(word_count):
                        line[j] += " " * spaces_per_word
        
                    return " ".join(line)
        
                result = []
                i = 0
                while i < words_count:
                    line, line_length = get_line(i)
                    i += len(line)
                    result.append(create_line(line, line_length, i))
        
                return result
        

        4.7.1296 - 2023-09-01 18:38:28 +0300 MSK

        Course Schedule

        Code

        class Solution:
            def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
                
                nodes = [[] for _ in range(numCourses)]
                for target, required in prerequisites:
                    nodes[target].append(required)
        
                visited = set()
        
                @cache
                def dfs(course: int) -> bool:
                    if course in visited:
                        return False
            
                    edges = nodes[course]
                    if not edges:
                        return True
                    
                    visited.add(course)
                    return all(dfs(edge) for edge in edges)
        
                for course in range(numCourses):
                    if not dfs(course):
                        return False
                    visited.clear()
                
                return True
        

        4.7.1297 - 2023-09-01 18:37:48 +0300 MSK

        Course Schedule

        Code

        class Solution:
            def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
                
                nodes = [[] for _ in range(numCourses)]
                for target, required in prerequisites:
                    nodes[target].append(required)
        
                visited = set()
        
                @cache
                def dfs(course: int) -> bool:
                    if course in visited:
                        return False
            
                    edges = nodes[course]
                    if not edges:
                        return True
                    
                    visited.add(course)
                    return all(dfs(edge) for edge in edges)
        
                for course in range(numCourses):
                    if not dfs(course):
                        return False
                    visited.clear()
                
                return True
        

        4.7.1298 - 2023-09-01 09:58:21 +0300 MSK

        Counting Bits

        Code

        class Solution:
            def countBits(self, n: int) -> List[int]:
                ans = [0] * (n + 1)
                for i in range(1, n + 1):
                    ans[i] = ans[i >> 1] + (i & 1)
                return ans
        

        4.7.1299 - 2023-09-01 09:55:13 +0300 MSK

        Counting Bits

        Code

        class Solution:
            def countBits(self, n: int) -> List[int]:
                return tuple(bin(i).count("1") for i in range(n + 1))
        

        4.7.1300 - 2023-08-31 22:14:58 +0300 MSK

        Evaluate Division

        Code

        class Solution:
            def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
                equations_count = len(equations)
                queries_count = len(queries) 
                edges = defaultdict(dict)
                seen_nodes = set()
                invalid = -1.0
        
                def dfs(val1: str, val2: str) -> float:
                    if val1 == val2:
                        return 1.0
        
                    if val2 in edges[val1]:
                        return edges[val1][val2]
        
                    if val1 in seen_nodes:
                        return invalid
        
                    seen_nodes.add(val1)
        
                    for connected_node in edges[val1]:
                        new_edge_res = dfs(connected_node, val2)
                        if new_edge_res == invalid:
                            continue
                        new_edge_res *= edges[val1][connected_node]
                        edges[val1][val2] = new_edge_res
                        return new_edge_res
                    
                    return invalid
        
                for i in range(equations_count):
                    (val1, val2), res = equations[i], values[i]
                    edges[val1][val2], edges[val2][val1] = res, 1 / res
                
                for i in range(queries_count):
                    res, (val1, val2) = -1, queries[i]
                    if val1 in edges and val2 in edges:
                        seen_nodes.clear()
                        res = dfs(val1, val2)
                    queries[i] = res
        
                return queries
        

        4.7.1301 - 2023-08-31 20:45:02 +0300 MSK

        Clone Graph

        Code

        """
        # Definition for a Node.
        class Node:
            def __init__(self, val = 0, neighbors = None):
                self.val = val
                self.neighbors = neighbors if neighbors is not None else []
        """
        
        class Solution:
            def cloneGraph(self, node: 'Node') -> 'Node':
                old_to_new = {}
                
                def clone(node: Node) -> Node:
                    if node in old_to_new:
                        return old_to_new[node]
                    
                    new_node = Node(node.val)
                    old_to_new[node] = new_node
                    new_node.neighbors = [clone(neighbor) for neighbor in node.neighbors]
        
                    return new_node
        
                return clone(node) if node else node
        

        4.7.1302 - 2023-08-31 20:35:52 +0300 MSK

        Surrounded Regions

        Code

        class Solution:
            def solve(self, board: List[List[str]]) -> None:
                """
                Do not return anything, modify board in-place instead.
                """
                row_count, col_count = len(board), len(board[0])
                moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
                ignore_cells = set()
        
                def bfs(row: int, col: int) -> None:
                    if not 0 <= row < row_count or not 0 <= col < col_count:
                        return
                    if (row, col) in ignore_cells or board[row][col] == "X":
                        return
        
                    ignore_cells.add((row, col))
                    for row_delta, col_delta in moves:
                        bfs(row + row_delta, col + col_delta)
                
                for row, col in itertools.chain(
                    ((0, col) for col in range(col_count)),
                    ((row_count - 1, col) for col in range(col_count)),
                    ((row, 0) for row in range(row_count)),
                    ((row, col_count - 1) for row in range(row_count))
                ):
                    bfs(row, col)
                
                for row in range(1, row_count - 1):
                    for col in range(1, col_count - 1):
                        if (row, col) in ignore_cells:
                            continue
        
                        board[row][col] = "X"
                
        

        4.7.1303 - 2023-08-31 20:35:00 +0300 MSK

        Surrounded Regions

        Code

        class Solution:
            def solve(self, board: List[List[str]]) -> None:
                """
                Do not return anything, modify board in-place instead.
                """
                row_count, col_count = len(board), len(board[0])
                moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
                ignore_stack = set()
        
                def bfs(row: int, col: int) -> None:
                    if not 0 <= row < row_count or not 0 <= col < col_count:
                        return
                    if (row, col) in ignore_stack or board[row][col] == "X":
                        return
        
                    ignore_stack.add((row, col))
                    for row_delta, col_delta in moves:
                        bfs(row + row_delta, col + col_delta)
                
                for row, col in itertools.chain(
                    ((0, col) for col in range(col_count)),
                    ((row_count - 1, col) for col in range(col_count)),
                    ((row, 0) for row in range(row_count)),
                    ((row, col_count - 1) for row in range(row_count))
                ):
                    bfs(row, col)
                
                flip_x = True
                for row in range(1, row_count - 1):
                    for col in range(1, col_count - 1):
                        if (row, col) in ignore_stack:
                            continue
        
                        board[row][col] = "X"
                
        

        4.7.1304 - 2023-08-31 20:34:31 +0300 MSK

        Surrounded Regions

        Code

        class Solution:
            def solve(self, board: List[List[str]]) -> None:
                """
                Do not return anything, modify board in-place instead.
                """
                row_count, col_count = len(board), len(board[0])
                moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
                ignore_stack = set()
        
                @cache
                def bfs(row: int, col: int) -> None:
                    if not 0 <= row < row_count or not 0 <= col < col_count:
                        return
                    if (row, col) in ignore_stack or board[row][col] == "X":
                        return
        
                    ignore_stack.add((row, col))
                    for row_delta, col_delta in moves:
                        bfs(row + row_delta, col + col_delta)
                
                for row, col in itertools.chain(
                    ((0, col) for col in range(col_count)),
                    ((row_count - 1, col) for col in range(col_count)),
                    ((row, 0) for row in range(row_count)),
                    ((row, col_count - 1) for row in range(row_count))
                ):
                    bfs(row, col)
                
                flip_x = True
                for row in range(1, row_count - 1):
                    for col in range(1, col_count - 1):
                        if (row, col) in ignore_stack:
                            continue
        
                        board[row][col] = "X"
                
        

        4.7.1305 - 2023-08-31 15:29:43 +0300 MSK

        Minimum Number of Taps to Open to Water a Garden

        Code

        class Solution:
            def minTaps(self, n: int, ranges: List[int]) -> int:
                inf = float("inf")
                dp = [inf] * (n + 1)
                dp[0] = 0
                
                for i in range(n + 1):
                    cur_range = ranges[i]
                    tap_start, tap_end = max(0, i - cur_range), min(n, i + cur_range)
                    
                    for j in range(tap_start, tap_end + 1):
                        dp[tap_end] = min(dp[tap_end], dp[j] + 1)
                
                min_taps = dp[n]
                return -1 if min_taps == inf else min_taps 
        

        4.7.1306 - 2023-08-31 12:14:40 +0300 MSK

        Minimum Number of Taps to Open to Water a Garden

        Code

        class Solution:
            def minTaps(self, n: int, ranges: List[int]) -> int:
                arr = [0] * (n + 1)
                for i, r in enumerate(ranges):
                    if r == 0:
                        continue
                    left = max(0, i - r)
                    arr[left] = max(arr[left], i + r)
        
                end, far_can_reach, cnt = 0, 0, 0
                
                for i, reach in enumerate(arr):
                    if i > end:
                        if far_can_reach <= end:
                            return -1
                        end, cnt = far_can_reach, cnt + 1
                    far_can_reach = max(far_can_reach, reach)
        
                return cnt + (end < n)
        

        4.7.1307 - 2023-08-30 19:06:25 +0300 MSK

        Minimum Replacements to Sort the Array

        Code

        class Solution:
            def minimumReplacement(self, nums: List[int]) -> int:
                nums_count = len(nums)
                operations_count = 0
                for i in reversed(range(nums_count - 1)):
                    cur, prev = nums[i], nums[i+1]
                    if cur <= prev:
                        continue
                    
                    elements_count = (cur + prev - 1) // prev
                    operations_count += elements_count - 1
                    nums[i] //= elements_count
        
                return operations_count
        

        4.7.1308 - 2023-08-29 19:00:49 +0300 MSK

        Number of Islands

        Code

        class Solution:
            def numIslands(self, grid: List[List[str]]) -> int:
                row_count, col_count = len(grid), len(grid[0])
                island_count = 0
                moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
        
                @cache
                def dfs(row: int, col: int) -> None:
                    if not 0 <= row < row_count or not 0 <= col < col_count or grid[row][col] == "0":
                        return
                    
                    grid[row][col] = "0"
                    for row_delta, col_delta in moves:
                        dfs(row + row_delta, col + col_delta)
        
                for row in range(row_count):
                    for col in range(col_count):
                        if grid[row][col] == "0":
                            continue
        
                        dfs(row, col)
                        island_count += 1
        
                return island_count
        
                    
        

        4.7.1309 - 2023-08-29 18:48:22 +0300 MSK

        Number of Islands

        Code

        class Solution:
            def numIslands(self, grid: List[List[str]]) -> int:
                row_count, col_count = len(grid), len(grid[0])
                island_count = 0
                moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
                queue = set((row, col) 
                            for row in range(row_count) 
                            for col in range(col_count) 
                            if grid[row][col] == "1")
        
                @cache
                def remove_island(row: int, col: int) -> None:
                    if not 0 <= row < row_count or not 0 <= col < col_count:
                        return
        
                    for row_delta, col_delta in moves:
                        new_cell = (row + row_delta, col + col_delta)
                        if new_cell in queue:
                            queue.remove(new_cell)
                            remove_island(*new_cell)
        
                while queue:
                    remove_island(*queue.pop())
                    island_count += 1
        
                return island_count
        
                    
        

        4.7.1310 - 2023-08-29 18:48:09 +0300 MSK

        Number of Islands

        Code

        class Solution:
            def numIslands(self, grid: List[List[str]]) -> int:
                row_count, col_count = len(grid), len(grid[0])
                island_count = 0
                moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
                queue = set((row, col) 
                            for row in range(row_count) 
                            for col in range(col_count) 
                            if grid[row][col] == "1")
        
                @cache
                def remove_island(row: int, col: int) -> None:
                    if not 0 <= row < row_count or not 0 <= col < col_count:
                        return
        
                    for row_delta, col_delta in moves:
                        new_cell = (row + row_delta, col + col_delta)
                        if new_cell in queue:
                            queue.remove(new_cell)
                            remove_island(*new_cell)
        
                while queue:
                    remove_island(*queue.pop())
                    island_count += 1
        
                return island_count
        
                    
        

        4.7.1311 - 2023-08-29 18:44:17 +0300 MSK

        Number of Islands

        Code

        class Solution:
            def numIslands(self, grid: List[List[str]]) -> int:
                row_count, col_count = len(grid), len(grid[0])
                island_count = 0
                moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
                queue = set((row, col) 
                            for row in range(row_count) 
                            for col in range(col_count) 
                            if grid[row][col] == "1")
        
                def remove_island(row: int, col: int) -> None:
                    if not 0 <= row < row_count or not 0 <= col < col_count or (row, col) not in queue:
                        return
        
                    queue.remove((row, col))
        
                    for row_delta, col_delta in moves:
                        remove_island(row + row_delta, col + col_delta)    
        
                while queue:
                    remove_island(*next(iter(queue)))
                    island_count += 1
        
                return island_count
        
                    
        

        4.7.1312 - 2023-08-29 18:43:22 +0300 MSK

        Number of Islands

        Code

        class Solution:
            def numIslands(self, grid: List[List[str]]) -> int:
                row_count, col_count = len(grid), len(grid[0])
                island_count = 0
                moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
                queue = set((row, col) 
                            for row in range(row_count) 
                            for col in range(col_count) 
                            if grid[row][col] == "1")
        
                @cache
                def remove_island(row: int, col: int) -> None:
                    if not 0 <= row < row_count or not 0 <= col < col_count or (row, col) not in queue:
                        return
        
                    queue.remove((row, col))
        
                    for row_delta, col_delta in moves:
                        remove_island(row + row_delta, col + col_delta)    
        
                while queue:
                    remove_island(*next(iter(queue)))
                    island_count += 1
        
                return island_count
        
                    
        

        4.7.1313 - 2023-08-29 11:50:54 +0300 MSK

        Minimum Penalty for a Shop

        Code

        class Solution:
            def bestClosingTime(self, customers: str) -> int:
                # Start with closing at hour 0, the penalty equals all 'Y' in closed hours.
                cur_penalty = min_penalty = customers.count("Y")
                earliest_hour = 0
                
                for hour, customer in enumerate(customers):
                    # If status in hour i is 'Y', moving it to open hours decrement
                    # penalty by 1. Otherwise, moving 'N' to open hours increment
                    # penatly by 1.
                    cur_penalty += 1 if customer == "N" else -1
        
                    # Update earliest_hour if a smaller penatly is encountered
                    if cur_penalty < min_penalty:
                        earliest_hour = hour + 1
                        min_penalty = cur_penalty
                        
                return earliest_hour
        

        4.7.1314 - 2023-08-28 13:37:58 +0300 MSK

        Map Sum Pairs

        Code

        class MapSum:
        
            def __init__(self):
                self._map = {}
        
            def insert(self, key: str, val: int) -> None:
                self._map[key] = val
        
            def sum(self, prefix: str) -> int:
                return sum(value for key, value in self._map.items() if key.startswith(prefix))
        
        
        # Your MapSum object will be instantiated and called as such:
        # obj = MapSum()
        # obj.insert(key,val)
        # param_2 = obj.sum(prefix)
        

        4.7.1315 - 2023-08-28 13:35:54 +0300 MSK

        Implement Stack using Queues

        Code

        class MyStack:
        
            def __init__(self):
                self._queue = []
        
            def push(self, x: int) -> None:
                self._queue.append(x)
        
            def pop(self) -> int:
                return self._queue.pop()
        
            def top(self) -> int:
                return self._queue[-1]
        
            def empty(self) -> bool:
                return len(self._queue) == 0 
        
        
        # Your MyStack object will be instantiated and called as such:
        # obj = MyStack()
        # obj.push(x)
        # param_2 = obj.pop()
        # param_3 = obj.top()
        # param_4 = obj.empty()
        

        4.7.1316 - 2023-08-27 18:09:36 +0300 MSK

        Minimum Absolute Difference in BST

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
                
                def min_node_diff(node: TreeNode, low: int, high: int) -> int:
                    if not node:
                        return high - low
        
                    return min(min_node_diff(node.left, low, node.val),
                               min_node_diff(node.right, node.val, high))
            
                return min_node_diff(root, -maxsize, maxsize)
        

        4.7.1317 - 2023-08-27 18:03:23 +0300 MSK

        Minimum Absolute Difference in BST

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
                values = []
                def fall(node: TreeNode) -> None:
                    if not node:
                        return
                    values.append(node.val)
                    if node.left:
                        fall(node.left)
                    if node.right:
                        fall(node.right)
                
                fall(root)
                values.sort()
                min_diff = abs(values[1] - values[0])
                for i in range(1, len(values) - 1):
                    min_diff = min(min_diff, abs(values[i] - values[i+1]))
                
                return min_diff
        

        4.7.1318 - 2023-08-27 17:55:09 +0300 MSK

        Frog Jump

        Code

        class Solution:
            def canCross(self, stones: List[int]) -> bool:
                m = set(stones)
                @cache
                def dfs(i, j):
                    if i == stones[-1]: return True
                    return any(x and x + i in m and dfs(x + i, x) for x in range(j - 1, j + 2))
                return dfs(0, 0)
        

        4.7.1319 - 2023-08-26 16:17:44 +0300 MSK

        Count Complete Tree Nodes

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def countNodes(self, root: Optional[TreeNode]) -> int:
                def left_height(root: TreeNode) -> int:
                    return 0 if not root else 1 + left_height(root.left)
                
                def right_height(root: TreeNode) -> int:
                    return 0 if not root else 1 + right_height(root.right)
                
                left, right = left_height(root), right_height(root)
                if left > right:
                    return 1 + self.countNodes(root.left) + self.countNodes(root.right)
                
                return 2**left - 1
        
                
        

        4.7.1320 - 2023-08-26 16:17:28 +0300 MSK

        Count Complete Tree Nodes

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def countNodes(self, root: Optional[TreeNode]) -> int:
                def left_height(root: TreeNode) -> int:
                    return 0 if not root else 1 + left_height(root.left)
                
                def right_height(root: TreeNode) -> int:
                    return 0 if not root else 1+ right_height(root.right)
                
                left, right = left_height(root), right_height(root)
                if left > right:
                    return 1 + self.countNodes(root.left) + self.countNodes(root.right)
                
                return 2**left - 1
        
                
        

        4.7.1321 - 2023-08-26 16:16:46 +0300 MSK

        Count Complete Tree Nodes

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def countNodes(self, root: Optional[TreeNode]) -> int:
                if not root:
                    return 0
                
                def left_height(root: TreeNode) -> int:
                    return 0 if not root else 1 + left_height(root.left)
                
                def right_height(root: TreeNode) -> int:
                    return 0 if not root else 1+ right_height(root.right)
                
                left, right = left_height(root), right_height(root)
                if left > right:
                    return 1 + self.countNodes(root.left) + self.countNodes(root.right)
                
                return 2**left - 1
        
                
        

        4.7.1322 - 2023-08-26 16:06:04 +0300 MSK

        Path Sum

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
                node_stack = [(root, 0)]
                while node_stack:
                    node, curr_sum = node_stack.pop()
                    if not node:
                        continue
                    
                    new_sum = curr_sum + node.val
                    if new_sum == targetSum and not node.left and not node.right:
                        return True
                    
                    node_stack.extend(((node.left, new_sum), (node.right, new_sum)))
                        
                return False
        

        4.7.1323 - 2023-08-26 15:38:12 +0300 MSK

        Symmetric Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def isSymmetric(self, root: Optional[TreeNode]) -> bool:
                comparison_stack = [(root.left, root.right)]
                while comparison_stack:
                    left, right = comparison_stack.pop()
                    
                    if not left and not right:
                        continue
                    if not left or not right or left.val != right.val:
                        return False
        
                    comparison_stack.extend(((left.left, right.right), (left.right, right.left)))
                
                return True
        

        4.7.1324 - 2023-08-26 15:24:31 +0300 MSK

        Symmetric Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def isSymmetric(self, root: Optional[TreeNode]) -> bool:
                return self.check(root.left, root.right)
        
            def check(self, left: TreeNode, right: TreeNode) -> bool:
                if not left and not right:
                    return True
                
                if not left or not right or left.val != right.val:
                    return False
                
                return self.check(left.left, right.right) and self.check(left.right, right.left)
        

        4.7.1325 - 2023-08-26 15:20:18 +0300 MSK

        Invert Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
                if root:
                    root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
                return root
        

        4.7.1326 - 2023-08-26 15:20:08 +0300 MSK

        Invert Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
                if root:
                    root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
                return root 
        

        4.7.1327 - 2023-08-26 15:19:33 +0300 MSK

        Invert Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
                if not root:
                    return None
        
                root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
                return root 
        

        4.7.1328 - 2023-08-26 15:18:57 +0300 MSK

        Invert Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
                if not root:
                    return None
        
                self.invertTree(root.left)
                self.invertTree(root.right) 
                root.left, root.right = root.right, root.left
                
                return root 
        

        4.7.1329 - 2023-08-26 12:16:27 +0300 MSK

        Maximum Length of Pair Chain

        Code

        class Solution:
            def findLongestChain(self, pairs: List[List[int]]) -> int:
                pairs_count = len(pairs)
                if pairs_count < 2:
                    return pairs_count
                
                pairs.sort()
                
                @cache
                def dp(curr_pair: int) -> int:
                    right = pairs[curr_pair][1]
                    max_length = 1
        
                    for new_pair in range(curr_pair + 1, pairs_count):
                        new_left = pairs[new_pair][0]
                        new_length = dp(new_pair) + (1 if new_left > right else 0)
        
                        if new_length > max_length:
                            max_length = new_length
                    
                    return max_length
                
                return dp(0)
        

        4.7.1330 - 2023-08-25 10:04:50 +0300 MSK

        Interleaving String

        Code

        class Solution:
            def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
                length_1, length_2, length_3 = len(s1), len(s2), len(s3)
                if length_1 + length_2 != length_3:
                    return False
        
                @cache
                def dp(i_1: int, i_2: int, i_3: int) -> bool:
                    if i_3 == length_3:
                        return True
        
                    target = s3[i_3]
                    return (
                        i_1 != length_1 and s1[i_1] == target and dp(i_1 + 1, i_2, i_3 + 1)
                    ) or (
                        i_2 != length_2 and s2[i_2] == target and dp(i_1, i_2 + 1, i_3 + 1)
                    )
        
                return dp(0, 0, 0)
        

        4.7.1331 - 2023-08-24 16:42:07 +0300 MSK

        Find K Pairs with Smallest Sums

        Code

        class Solution:
            def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
                nums1_count, nums2_count = len(nums1), len(nums2)
                result = []
                visited = set(((0, 0)))
                min_heap = [(nums1[0] + nums2[0], (0, 0))]
                count = 0
        
                while k > 0 and min_heap:
                    _, (i, j) = heappop(min_heap)
                    new_i, new_j = i + 1, j + 1
                    new_pair1, new_pair2 = (new_i, j), (i, new_j)
                    num1, num2 = nums1[i], nums2[j]
                    result.append((num1, num2))
        
                    if new_i < nums1_count and new_pair1 not in visited:
                        heappush(min_heap, (nums1[new_i] + num2, new_pair1))
                        visited.add(new_pair1)
        
                    if new_j < nums2_count and new_pair2 not in visited:
                        heappush(min_heap, (num1 + nums2[new_j], new_pair2))
                        visited.add(new_pair2)
        
                    k -= 1
                
                return result
        

        4.7.1332 - 2023-08-24 13:45:42 +0300 MSK

        Text Justification

        Code

        class Solution:
            def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
                words_count = len(words)
                
                def get_line(word_idx: int) -> Tuple[List[str], int]:
                    line = []
                    line_length = 0
        
                    for i in range(word_idx, words_count):
                        word = words[i]
                        word_length = len(word)
                        if line_length + word_length > maxWidth:
                            break
        
                        line.append(word)
                        line_length += word_length + 1 
        
                    return line, line_length
                
                def create_line(line: List[str], line_length: int, word_idx: int) -> str:
                    base_length = line_length - 1
                    extra_spaces = maxWidth - base_length
        
                    if len(line) == 1 or word_idx == words_count:
                        return " ".join(line) + " " * extra_spaces
        
                    word_count = len(line) - 1
                    spaces_per_word = extra_spaces // word_count
                    needs_extra_space = extra_spaces % word_count
        
                    for j in range(needs_extra_space):
                        line[j] += " "
        
                    for j in range(word_count):
                        line[j] += " " * spaces_per_word
        
                    return " ".join(line)
        
                result = []
                i = 0
                while i < words_count:
                    line, line_length = get_line(i)
                    i += len(line)
                    result.append(create_line(line, line_length, i))
        
                return result
        

        4.7.1333 - 2023-08-23 22:56:37 +0300 MSK

        Summary Ranges

        Code

        class Solution:
            def summaryRanges(self, nums: List[int]) -> List[str]:
                nums_count = len(nums)
                if nums_count == 0:
                    return []
                if nums_count == 1:
                    return [str(nums[0])]
        
                ranges = [[nums[0]] * 2]
                for i, num in enumerate(nums[1:]):
                    if ranges[-1][1] == num - 1:
                        ranges[-1][1] = num
                    else:
                        ranges.append([num, num])
        
                return [f"{start}->{end}" if start != end else str(start) for start, end in ranges]
        

        4.7.1334 - 2023-08-23 12:45:05 +0300 MSK

        Reorganize String

        Code

        class Solution:
            def reorganizeString(self, s: str) -> str:
                result = []
                # Min heap ordered by character counts, so we will use
                # negative values for count
                priority_queue = [(-count, char) for char, count in Counter(s).items()]
                heapify(priority_queue)
        
                while priority_queue:
                    count_first, char_first = heappop(priority_queue)
                    if not result or char_first != result[-1]:
                        result.append(char_first)
                        if count_first != -1: 
                            heappush(priority_queue, (count_first + 1, char_first))
                        continue
                    
                    if not priority_queue: 
                        return ""
                    
                    count_second, char_second = heappop(priority_queue)
                    result.append(char_second)
                    if count_second != -1:
                        heappush(priority_queue, (count_second + 1, char_second))
                    heappush(priority_queue, (count_first, char_first))
        
                return "".join(result)
        

        4.7.1335 - 2023-08-22 10:32:27 +0300 MSK

        Excel Sheet Column Title

        Code

        class Solution:
            def convertToTitle(self, columnNumber: int) -> str:
                result = []
                while columnNumber:
                    columnNumber, remainder = divmod(columnNumber - 1, 26)
                    result.append(chr(65 + remainder))
                return ''.join(reversed(result))
        

        4.7.1336 - 2023-08-21 23:38:46 +0300 MSK

        Spiral Matrix

        Code

        class Solution:
            def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
                row_count, col_count = len(matrix), len(matrix[0])
                if row_count == 1:
                    return matrix[0]
                if col_count == 1:
                    return [row[0] for row in matrix]
        
        
                result = []
                top, bot, left, right = 0, row_count - 1, 0, col_count - 1
                capacity = row_count * col_count
        
                while len(result) < capacity:
                    for col in range(left, right + 1):
                        result.append(matrix[top][col])
                    top += 1
        
                    for row in range(top, bot + 1):
                        result.append(matrix[row][right])
                    right -= 1
        
                    if top <= bot:
                        for col in range(right, left - 1, -1):
                            result.append(matrix[bot][col])
                        bot -= 1
                    
                    if left <= right:
                        for row in range(bot, top - 1, -1):
                            result.append(matrix[row][left])
                        left += 1
        
                return result
        

        4.7.1337 - 2023-08-21 21:08:48 +0300 MSK

        Valid Sudoku

        Code

        class Solution:
            def isValidSudoku(self, board: List[List[str]]) -> bool:
                row_count, column_count = 9, 9
                row_counters = [defaultdict(bool) for _ in range(row_count)]
                column_counters = [defaultdict(bool) for _ in range(column_count)]
                subbox_counters = [[defaultdict(bool) for _ in range(column_count//3)] 
                                    for _ in range(row_count//3)]
        
                for row in range(row_count):
                    for column in range(column_count):
                        char = board[row][column]
                        if char == ".":
                            continue
        
                        counters = (
                            row_counters[row], column_counters[column], 
                            subbox_counters[row//3][column//3]
                        )
                        for counter in counters:
                            if counter[char]:
                                return False
        
                            counter[char] = True
                
                return True
        
                
        

        4.7.1338 - 2023-08-21 21:08:11 +0300 MSK

        Valid Sudoku

        Code

        class Solution:
            def isValidSudoku(self, board: List[List[str]]) -> bool:
                row_count, column_count = 9, 9
        
                
        
                row_counters = [defaultdict(bool) for _ in range(row_count)]
                column_counters = [defaultdict(bool) for _ in range(column_count)]
                subbox_counters = [[defaultdict(bool) for _ in range(column_count//3)] 
                                    for _ in range(row_count//3)]
        
                for row in range(row_count):
                    for column in range(column_count):
                        char = board[row][column]
                        if char == ".":
                            continue
        
                        counters = (
                            row_counters[row], column_counters[column], 
                            subbox_counters[row//3][column//3]
                        )
                        for counter in counters:
                            if counter[char]:
                                return False
        
                            counter[char] = True
                
                return True
        
                
        

        4.7.1339 - 2023-08-21 09:29:54 +0300 MSK

        Repeated Substring Pattern

        Code

        class Solution:
            def repeatedSubstringPattern(self, s: str) -> bool:
                length = len(s)
                for i in range(1, length // 2 + 1):
                    if length % i != 0:
                        continue
                    
                    if s == s[:i] * (length // i):
                        return True
                
                return False
        

        4.7.1340 - 2023-08-20 14:34:41 +0300 MSK

        Sort Items by Groups Respecting Dependencies

        Code

        class Solution:
            def sortItems(self, n, m, group, beforeItems):
                # If an item belongs to zero group, assign it a unique group id.
                group_id = m
                for i in range(n):
                    if group[i] == -1:
                        group[i] = group_id
                        group_id += 1
                
                # Sort all item regardless of group dependencies.
                item_graph = [[] for _ in range(n)]
                item_indegree = [0] * n
                
                # Sort all groups regardless of item dependencies.
                group_graph = [[] for _ in range(group_id)]
                group_indegree = [0] * group_id      
                
                for curr in range(n):
                    for prev in beforeItems[curr]:
                        # Each (prev -> curr) represents an edge in the item graph.
                        item_graph[prev].append(curr)
                        item_indegree[curr] += 1
                        
                        # If they belong to different groups, add an edge in the group graph.
                        if group[curr] != group[prev]:
                            group_graph[group[prev]].append(group[curr])
                            group_indegree[group[curr]] += 1      
                
                # Tologlogical sort nodes in graph, return [] if a cycle exists.
                def topologicalSort(graph, indegree):
                    visited = []
                    stack = [node for node in range(len(graph)) if indegree[node] == 0]
                    while stack:
                        cur = stack.pop()
                        visited.append(cur)
                        for neib in graph[cur]:
                            indegree[neib] -= 1
                            if indegree[neib] == 0:
                                stack.append(neib)
                    return visited if len(visited) == len(graph) else []
        
                item_order = topologicalSort(item_graph, item_indegree)
                group_order = topologicalSort(group_graph, group_indegree)
                
                if not item_order or not group_order: 
                    return []
                
                # Items are sorted regardless of groups, we need to 
                # differentiate them by the groups they belong to.
                ordered_groups = collections.defaultdict(list)
                for item in item_order:
                    ordered_groups[group[item]].append(item)
                
                # Concatenate sorted items in all sorted groups.
                # [group 1, group 2, ... ] -> [(item 1, item 2, ...), (item 1, item 2, ...), ...]
                answer = []
                for group_index in group_order:
                    answer += ordered_groups[group_index]
                return answer
        

        4.7.1341 - 2023-08-19 18:48:22 +0300 MSK

        Sorting Three Groups

        Code

        class Solution:
            def minimumOperations(self, nums: List[int]) -> int:
                nums_count = len(nums)
                
                if nums_count == 1:
                    return 0
                    
                @cache
                def dp(i: int, start_group: int) -> int:
                    if i == nums_count:
                        return 0
                    
                    curr_group = nums[i] - 1
                    actions_min = None
                    
                    for group_available in range(start_group, 3):
                        actions = dp(i + 1, group_available) + (0 if group_available == curr_group else 1)
                        if actions_min is None or actions < actions_min:
                            actions_min = actions
                    
                    return actions_min
                
                return dp(0, 0)
        

        4.7.1342 - 2023-08-19 18:13:19 +0300 MSK

        Make String a Subsequence Using Cyclic Increments

        Code

        class Solution:
            def canMakeSubsequence(self, str1: str, str2: str) -> bool:
                length1, length2 = len(str1), len(str2)
                
                for i in range(length1):
                    if i + length2 > length1:
                        break
                    
                    idx2 = 0
                    for idx1 in range(i, length1):
                        if ord(str2[idx2]) - ord(str1[idx1]) in (0, 1, -25):
                            idx2 += 1
                        
                        if idx2 == length2:
                            return True
                    
                    
                return False
        

        4.7.1343 - 2023-08-19 17:36:50 +0300 MSK

        Count Pairs Whose Sum is Less than Target

        Code

        class Solution:
            def countPairs(self, nums: List[int], target: int) -> int:
                pairs_count = 0
                nums_count = len(nums)
                for i in range(nums_count): 
                    num1 = nums[i]
                    for j in range(i + 1, nums_count):
                        if num1 + nums[j] < target:
                            pairs_count += 1
                
                return pairs_count
        

        4.7.1344 - 2023-08-19 17:13:39 +0300 MSK

        Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree

        Code

        class Solution:
        
            class UnionFind:
                def __init__(self, n):
                    self.parent = list(range(n))
                    self.size = [1] * n
                    self.max_size = 1
        
                def find(self, x):
                    # Finds the root of x
                    if x != self.parent[x]:
                        self.parent[x] = self.find(self.parent[x])
                    return self.parent[x]
        
                def union(self, x, y):
                    # Connects x and y
                    root_x = self.find(x)
                    root_y = self.find(y)
                    if root_x != root_y:
                        if self.size[root_x] < self.size[root_y]:
                            root_x, root_y = root_y, root_x
                        self.parent[root_y] = root_x
                        self.size[root_x] += self.size[root_y]
                        self.max_size = max(self.max_size, self.size[root_x])
                        return True
                    return False
        
            def findCriticalAndPseudoCriticalEdges(self, n, edges):
                new_edges = [edge.copy() for edge in edges]
                # Add index to edges for tracking
                for i, edge in enumerate(new_edges):
                    edge.append(i)
                # Sort edges based on weight
                new_edges.sort(key=lambda x: x[2])
        
                # Find MST weight using union-find
                uf_std = self.UnionFind(n)
                std_weight = 0
                for u, v, w, _ in new_edges:
                    if uf_std.union(u, v):
                        std_weight += w
        
                # Check each edge for critical and pseudo-critical
                critical = []
                pseudo_critical = []
                for (u, v, w, i) in new_edges:
                    # Ignore this edge and calculate MST weight
                    uf_ignore = self.UnionFind(n)
                    ignore_weight = 0
                    for (x, y, w_ignore, j) in new_edges:
                        if i != j and uf_ignore.union(x, y):
                            ignore_weight += w_ignore
                    # If the graph is disconnected or the total weight is greater,
                    # the edge is critical
                    if uf_ignore.max_size < n or ignore_weight > std_weight:
                        critical.append(i)
                        continue
        
                    # Force this edge and calculate MST weight
                    uf_force = self.UnionFind(n)
                    force_weight = w
                    uf_force.union(u, v)
                    for (x, y, w_force, j) in new_edges:
                        if i != j and uf_force.union(x, y):
                            force_weight += w_force
                    # If total weight is the same, the edge is pseudo-critical
                    if force_weight == std_weight:
                        pseudo_critical.append(i)
        
                return [critical, pseudo_critical]
        

        4.7.1345 - 2023-08-18 10:52:33 +0300 MSK

        Maximal Network Rank

        Code

        class Solution:
            def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
                city_roads = [set() for _ in range(n)]
        
                for city_one, city_two in roads:
                    city_roads[city_one].add(city_two)
                    city_roads[city_two].add(city_one)
                
                max_rank = 0
        
                for city_one in range(n):
                    for city_two in range(city_one + 1, n):
                        rank = len(city_roads[city_one]) + len(city_roads[city_two])
                        if city_one in city_roads[city_two]:
                            rank -= 1
                        
                        if rank > max_rank:
                            max_rank = rank
                
                return max_rank
        

        4.7.1346 - 2023-08-17 16:52:59 +0300 MSK

        01 Matrix

        Code

        class Solution:
            def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
                if not mat or not mat[0]:
                    return []
        
                row_count, column_count = len(mat), len(mat[0])
                queue = set()
                MAX_VALUE = row_count * column_count
                
                # Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.
                for row in range(row_count):
                    for column in range(column_count):
                        if mat[row][column] == 0:
                            queue.add((row, column))
                        else:
                            mat[row][column] = MAX_VALUE
                
                directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
                
                while queue:
                    center_row, center_column = queue.pop()
                    distance_from_center = mat[center_row][center_column] + 1
        
                    for delta_row, delta_column in directions:
                        new_row, new_column = center_row + delta_row, center_column + delta_column
                        if not 0 <= new_row < row_count or not 0 <= new_column < column_count:
                            continue
            
                        if mat[new_row][new_column] > distance_from_center:
                            queue.add((new_row, new_column))
                            mat[new_row][new_column] = distance_from_center
                
                return mat
        

        4.7.1347 - 2023-08-16 14:36:21 +0300 MSK

        Sliding Window Maximum

        Code

        import sortedcontainers
        
        class Solution:
            def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
                nums_count = len(nums)
                if nums_count <= k:
                    return [max(nums)]
        
                counter = defaultdict(int)
                elems = sortedcontainers.SortedSet()
                
                for num in nums[:k]:
                    counter[num] += 1
                    elems.add(num)
                
                result = [elems[-1]]
                
                for i in range(k, nums_count):
                    new_num = nums[i]
                    remove_num = nums[i-k]
        
                    counter[new_num] += 1
                    elems.add(new_num)
        
                    counter[remove_num] -= 1
                    if counter[remove_num] == 0:
                        elems.discard(remove_num)
        
                    result.append(elems[-1])
        
                return result
        

        4.7.1348 - 2023-08-15 17:06:49 +0300 MSK

        Partition List

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
                before_head, after_head = ListNode(0), ListNode(0)
                before_tail, after_tail = before_head, after_head
                
                while head: 
                    if head.val < x:
                        before_tail.next, before_tail = head, head
                    else:
                        after_tail.next, after_tail = head, head
                    head = head.next
                
                after_tail.next, before_tail.next = None, after_head.next
                
                return before_head.next
        

        4.7.1349 - 2023-08-15 17:02:49 +0300 MSK

        Partition List

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
                first_left, last_left, first_right, last_right = None, None, None, None
        
                while head:
                    is_left = head.val < x
                    is_right = not is_left
                    next_node = head.next
                    head.next = first_right if is_left else None
                    
                    if is_left and last_left:
                        last_left.next = head
                        last_left = head
                    elif is_left and not first_left:
                        first_left, last_left = head, head
        
                    if is_right and first_right:
                        last_right.next = head
                        last_right = head
                    elif is_right and not first_right:
                        first_right, last_right = head, head
                        if last_left:
                            last_left.next = head
        
                    head = next_node
        
                return first_left if first_left else first_right
        

        4.7.1350 - 2023-08-14 11:17:39 +0300 MSK

        Kth Largest Element in an Array

        Code

        class Solution:
            def findKthLargest(self, nums, k):
                heap = []
                for num in nums:
                    heapq.heappush(heap, num)
                    if len(heap) > k:
                        heapq.heappop(heap)
                
                return heap[0]
        

        4.7.1351 - 2023-08-13 18:35:13 +0300 MSK

        Check if There is a Valid Partition For The Array

        Code

        class Solution:
            def validPartition(self, nums: List[int]) -> bool:
                n = len(nums)
                dp = [True] + [False] * n
        
                # Determine if the prefix array nums[0 ~ i] has a valid partition
                for i in range(n):
                    dp_index = i + 1
        
                    # Check 3 possibilities
                    if i > 0 and nums[i] == nums[i - 1]:
                        dp[dp_index] |= dp[dp_index - 2]
                    if i > 1 and nums[i] == nums[i - 1] == nums[i - 2]:
                        dp[dp_index] |= dp[dp_index - 3]
                    if i > 1 and nums[i] == nums[i - 1] + 1 == nums[i - 2] + 2:
                        dp[dp_index] |= dp[dp_index - 3]
         
                return dp[n]
        

        4.7.1352 - 2023-08-12 17:50:41 +0300 MSK

        Unique Paths II

        Code

        class Solution:
            def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
                row_count = len(obstacleGrid)
                column_count = len(obstacleGrid[0])
                
                if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1:
                    return 0
        
                dp = [[0] * column_count for _ in range(row_count)]
                dp[0][0] = 1
        
                for column in range(1, column_count):
                    if obstacleGrid[0][column] == 1:
                        break
        
                    dp[0][column] = dp[0][column-1]
        
                for row in range(1, row_count):
                    if obstacleGrid[row][0] == 0:
                        dp[row][0] = dp[row-1][0]
        
                    for column in range(1, column_count):
                        if obstacleGrid[row][column] == 1:
                            continue
                        
                        dp[row][column] = dp[row-1][column] + dp[row][column-1]
                             
                return dp[-1][-1]
        

        4.7.1353 - 2023-08-11 17:52:07 +0300 MSK

        3Sum

        Code

        class Solution:
            def threeSum(self, nums: List[int]) -> List[List[int]]:
                result = set()
        
                #1. Split nums into three lists: negative numbers, positive numbers, and zeros
                negatives, positives, zeros = [], [], []
                for num in nums:
                    if num > 0:
                        positives.append(num)
                    elif num < 0: 
                        negatives.append(num)
                    else:
                        zeros.append(num)
        
                #2. Create a separate set for negatives and positives for O(1) look-up times
                negatives_count, positives_count, zeros_count = len(negatives), len(positives), len(zeros)
                negatives_set, positives_set = set(negatives), set(positives)
        
                #3. If there is at least 1 zero in the list, add all cases where -num exists in N and num exists in P
                #   i.e. (-3, 0, 3) = 0
                for num in positives_set if zeros else []:
                    negative = -1 * num
                    if negative in negatives_set:
                        result.add((negative, 0, num))
        
                #3. If there are at least 3 zeros in the list then also include (0, 0, 0) = 0
                if zeros_count >= 3:
                    result.add((0, 0, 0))
        
                #4. For all pairs of negative numbers (-3, -1), check to see if their complement (4)
                #   exists in the positive number set
                for i in range(negatives_count):
                    negative_1 = negatives[i]
                    for j in range(i + 1, negatives_count):
                        negative_2 = negatives[j]
                        target = -1 * (negative_1 + negative_2)
                        if target in positives_set:
                            result.add(tuple(sorted([negative_1, negative_2, target])))
        
                #5. For all pairs of positive numbers (1, 1), check to see if their complement (-2)
                #   exists in the negative number set
                for i in range(positives_count):
                    positive_1 = positives[i]
                    for j in range(i + 1, positives_count):
                        positive_2 = positives[j]
                        target = -1 * (positive_1 + positive_2)
                        if target in negatives_set:
                            result.add(tuple(sorted([positive_1, positive_2, target])))
        
                return result
        

        4.7.1354 - 2023-08-11 12:05:33 +0300 MSK

        Product of Array Except Self

        Code

        class Solution:
            def productExceptSelf(self, nums: List[int]) -> List[int]:
                nums_count = len(nums)
                result = [1] * nums_count
                prefix = 1
                postfix = 1
                for i in range(nums_count):
                    result[i] *= prefix
                    prefix *= nums[i]
        
                    from_end = -1 * (i + 1)
                    result[from_end] *= postfix
                    postfix *= nums[from_end]
                
                return result
        

        4.7.1355 - 2023-08-11 12:01:50 +0300 MSK

        Product of Array Except Self

        Code

        class Solution:
            def productExceptSelf(self, nums: List[int]) -> List[int]:
                nums_count = len(nums)
                result = [1] * nums_count
                prefix = 1
                postfix = 1
                for i in range(nums_count):
                    result[i] *= prefix
                    prefix *= nums[i]
                    result[nums_count-i-1] *= postfix
                    postfix *= nums[nums_count-i-1]
                
                return result
        

        4.7.1356 - 2023-08-11 11:17:35 +0300 MSK

        Coin Change II

        Code

        class Solution:
            def change(self, amount: int, coins: List[int]) -> int:
                n = len(coins)
                dp = [[0] * (amount + 1) for _ in range(n + 1)]
                for i in range(n):
                    dp[i][0] = 1
        
                for i in range(n - 1, -1, -1):
                    for j in range(1, amount + 1):
                        if coins[i] > j:
                            dp[i][j] = dp[i + 1][j]
                        else:
                            dp[i][j] = dp[i + 1][j] + dp[i][j - coins[i]]
        
                return dp[0][amount]
        

        4.7.1357 - 2023-08-11 11:12:31 +0300 MSK

        Coin Change II

        Code

        class Solution:
            def change(self, amount: int, coins: List[int]) -> int:
                coins_count = len(coins)
                memo = [[-1] * (amount + 1) for _ in range(coins_count)]
                
                def dp(i: int, amount: int) -> int:
                    if amount == 0:
                        return 1
                    if i == coins_count:
                        return 0
                    if memo[i][amount] != -1:
                        return memo[i][amount]
        
                    value = None
        
                    if coins[i] > amount:
                        value = dp(i + 1, amount)
                    else:
                        value = dp(i, amount - coins[i]) + dp(i + 1, amount)
        
                    memo[i][amount] = value
                    return value
        
                return dp(0, amount)
        

        4.7.1358 - 2023-08-10 17:04:38 +0300 MSK

        Search in Rotated Sorted Array II

        Code

        class Solution:
            def search(self, nums: List[int], target: int) -> bool:
                left, right = 0, len(nums) - 1
                
                while left <= right:
                    mid = (left + right) // 2
                    
                    if nums[mid] == target:
                        return True
                    
                    if nums[mid] == nums[left]:
                        left += 1
                        continue
        
                    if nums[left] <= nums[mid]:
                        if nums[left] <= target < nums[mid]:
                            right = mid - 1
                        else:
                            left = mid + 1
                    else:
                        if nums[mid] < target <= nums[right]:
                            left = mid + 1
                        else:
                            right = mid - 1
                
                return False
        

        4.7.1359 - 2023-08-09 15:13:28 +0300 MSK

        Best Time to Buy and Sell Stock IV

        Code

        class Solution:
            def maxProfit(self, k: int, prices: List[int]) -> int:
                # no transaction, no profit
                if k == 0: return 0
                # dp[k][0] = min cost you need to spend at most k transactions
                # dp[k][1] = max profit you can achieve at most k transactions
                dp = [[1000, 0] for _ in range(k + 1)]
                for price in prices:
                    for i in range(1, k + 1):
                        # price - dp[i - 1][1] is how much you need to spend
                        # i.e use the profit you earned from previous transaction to buy the stock
                        # we want to minimize it
                        dp[i][0] = min(dp[i][0], price - dp[i - 1][1])
                        # price - dp[i][0] is how much you can achieve from previous min cost
                        # we want to maximize it
                        dp[i][1] = max(dp[i][1], price - dp[i][0])
                # return max profit at most k transactions
        		# or you can write `return dp[-1][1]`
                return dp[k][1]
        

        4.7.1360 - 2023-08-09 12:05:47 +0300 MSK

        Minimize the Maximum Difference of Pairs

        Code

        class Solution:
            def minimizeMax(self, nums: List[int], p: int) -> int:
                nums.sort()
                nums_count = len(nums)
                
                # Find the number of valid pairs by greedy approach
                def countValidPairs(threshold: int) -> int:
                    index, count = 0, 0
                    while index < nums_count - 1:
                        # If a valid pair is found, skip both numbers.
                        if nums[index + 1] - nums[index] <= threshold:
                            count += 1
                            index += 1
                        index += 1
                    return count
                
                left, right = 0, nums[-1] - nums[0]
                while left < right:
                    mid = left + (right - left) // 2
        
                    # If there are enough pairs, look for a smaller threshold.
                    # Otherwise, look for a larger threshold.
                    if countValidPairs(mid) >= p:
                        right = mid
                    else:
                        left = mid + 1
        
                return left       
        

        4.7.1361 - 2023-08-08 23:40:50 +0300 MSK

        Best Time to Buy and Sell Stock III

        Code

        class Solution:
        	def maxProfit(self, prices: List[int]) -> int:
        				
        		'''
        		dp_2_hold: max profit with 2 transactions, and in hold state
        		dp_2_not_hold: max profit with 2 transactions, and not in hold state
        		
        		dp_1_hold: max profit with 1 transaction, and in hold state
        		dp_1_not_hold: max profit with 1 transaction, and not in hold state
        		
        		Note: it is impossible to have stock in hand and sell on first day, therefore -infinity is set as initial profit value for hold state
        		'''
        		
        		dp_2_hold, dp_2_not_hold = -float('inf'), 0
        		dp_1_hold, dp_1_not_hold = -float('inf'), 0
        		
        		for stock_price in prices:
        				
        			# either keep being in not-hold state, or sell with stock price today
        			dp_2_not_hold = max( dp_2_not_hold, dp_2_hold + stock_price )
        	
        			# either keep being in hold state, or just buy with stock price today ( add one more transaction )
        			dp_2_hold = max( dp_2_hold, dp_1_not_hold - stock_price )
        				
        			# either keep being in not-hold state, or sell with stock price today
        			dp_1_not_hold = max( dp_1_not_hold, dp_1_hold + stock_price )
        	
        			# either keep being in hold state, or just buy with stock price today ( add one more transaction )
        			dp_1_hold = max( dp_1_hold, 0 - stock_price )
        				
        		return dp_2_not_hold
        

        4.7.1362 - 2023-08-08 23:36:48 +0300 MSK

        Best Time to Buy and Sell Stock III

        Code

        class Solution:
            def maxProfit(self, prices: List[int]) -> int:
                if not prices:
                    return 0
        
                # initialize variables for first buy, first sell, second buy, and second sell
                buy1, buy2 = float('inf'), float('inf')
                sell1, sell2 = 0, 0
        
                # iterate over prices to update buy and sell values
                for price in prices:
                    # update first buy and sell values
                    buy1 = min(buy1, price)
                    sell1 = max(sell1, price - buy1)
                    # update second buy and sell values
                    buy2 = min(buy2, price - sell1)
                    sell2 = max(sell2, price - buy2)
        
                return sell2
        

        4.7.1363 - 2023-08-08 22:57:16 +0300 MSK

        Longest Palindromic Substring

        Code

        class Solution:
            def longestPalindrome(self, s: str) -> str:
                n = len(s)
                dp = [[False] * n for _ in range(n)]
                ans = [0, 0]
                
                for i in range(n):
                    dp[i][i] = True
                
                for i in range(n - 1):
                    if s[i] == s[i + 1]:
                        dp[i][i + 1] = True
                        ans = [i, i + 1]
        
                for diff in range(2, n):
                    for i in range(n - diff):
                        j = i + diff
                        if s[i] == s[j] and dp[i + 1][j - 1]:
                            dp[i][j] = True
                            ans = [i, j]
        
                i, j = ans
                return s[i:j + 1]
        

        4.7.1364 - 2023-08-08 22:56:36 +0300 MSK

        Maximal Square

        Code

        class Solution:
            def maximalSquare(self, matrix: List[List[str]]) -> int:
                row_count, column_count = len(matrix), len(matrix[0])
                
                dp = [[0] * column_count for _ in range(row_count)]
                
                max_size = 0
                for column in range(column_count):
                    if matrix[0][column] == "0":
                        continue
                    dp[0][column] = 1
                    max_size = 1
        
                for row in range(row_count):
                    if matrix[row][0] == "0":
                        continue
                    dp[row][0] = 1
                    max_size = 1
                
                for row in range(1, row_count):
                    for column in range(1, column_count):
                        if matrix[row][column] == "0":
                            continue
                        
                        value = min(dp[row-1][column], dp[row][column-1], dp[row-1][column-1]) + 1
                        dp[row][column] = value
                        max_size = max(max_size, value)
                
                return max_size * max_size
        

        4.7.1365 - 2023-08-08 21:50:31 +0300 MSK

        Edit Distance

        Code

        class Solution:
            def minDistance(self, word1: str, word2: str) -> int:
                length1, length2 = len(word1), len(word2)
        
                @cache
                def dp(i1: int, i2: int) -> int:
                    if i1 == length1:
                        return length2 - (i2 + 1)
        
                    if i2 == length2:
                        return length1 - (i1 + 1)
                    
                    if word1[i1] == word2[i2]:
                        return dp(i1 + 1, i2 + 1)
        
                    return 1 + min((
                        # replace or insert
                        dp(i1 + 1, i2 + 1),
                        # remove from i1
                        dp(i1 + 1, i2),
                        # remove from i2
                        dp(i1, i2 + 1)
                    ))
                
                return dp(0, 0) + 1
        

        4.7.1366 - 2023-08-08 21:27:42 +0300 MSK

        Interleaving String

        Code

        class Solution:
            def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
                length_1, length_2, length_3 = len(s1), len(s2), len(s3)
                if length_1 + length_2 != length_3:
                    return False
                
                @cache
                def dp(i_1: int, i_2: int, i_3: int) -> bool:
                    if i_3 == length_3:
                        return True
        
                    target = s3[i_3]
                    return (
                        i_1 != length_1 and s1[i_1] == target and dp(i_1 + 1, i_2, i_3 + 1)
                    ) or (
                        i_2 != length_2 and s2[i_2] == target and dp(i_1, i_2 + 1, i_3 + 1)
                    )
        
                return dp(0, 0, 0)
        

        4.7.1367 - 2023-08-08 21:02:11 +0300 MSK

        Unique Paths II

        Code

        class Solution:
            def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
                row_count = len(obstacleGrid)
                column_count = len(obstacleGrid[0])
                
                if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1:
                    return 0
        
                dp = [[0] * column_count for _ in range(row_count)]
                dp[0][0] = 1
        
                for column in range(1, column_count):
                    if obstacleGrid[0][column] == 1:
                        break
        
                    dp[0][column] = dp[0][column-1]
        
                for row in range(1, row_count):
                    if obstacleGrid[row][0] == 0:
                        dp[row][0] = dp[row-1][0]
        
                    for column in range(1, column_count):
                        if obstacleGrid[row][column] == 1:
                            continue
                        
                        dp[row][column] = dp[row-1][column] + dp[row][column-1]
                             
                return dp[-1][-1]
        

        4.7.1368 - 2023-08-08 20:47:19 +0300 MSK

        Unique Paths II

        Code

        class Solution:
            def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
                row_count = len(obstacleGrid)
                column_count = len(obstacleGrid[0])
                # dp = [[0] * column_count for _ in range(row_count)]
        
                # for row in range(row_count):
                #     for column in range(column_count):
        
                @cache
                def dp(row: int, column: int) -> int:
                    if row == row_count or column == column_count or obstacleGrid[row][column] == 1:
                        return 0
                    
                    if row == row_count - 1 and column == column_count - 1:
                        return 1
                    
                    return dp(row + 1, column) + dp(row, column + 1)
                
                return dp(0, 0)
        

        4.7.1369 - 2023-08-08 20:31:21 +0300 MSK

        Minimum Path Sum

        Code

        class Solution:
            def minPathSum(self, grid: List[List[int]]) -> int:
                row_count = len(grid)
                column_count = len(grid[0]) if grid else None
                if not row_count or not column_count:
                    return 0
        
                dp = [[0] * column_count for _ in range(row_count)]
                dp[0][0] = grid[0][0]
        
                for column in range(1, column_count):
                    dp[0][column] = grid[0][column] + dp[0][column - 1]
        
                for row in range(1, row_count):
                    dp[row][0] = grid[row][0] + dp[row - 1][0]
        
                    for column in range(1, column_count):
                        dp[row][column] = grid[row][column] + min(
                            dp[row - 1][column], dp[row][column-1]
                        )
        
                # @cache
                # def dp(row: int, column: int) -> int:
                #     if row == row_count or column == column_count:
                #         return 0
                #     return grid[row][column] + min(dp(row + 1, column), dp(row, column + 1))
                #return dp(0, 0)
        
                return dp[-1][-1]
        

        4.7.1370 - 2023-08-08 19:53:50 +0300 MSK

        Triangle

        Code

        class Solution:
            def minimumTotal(self, triangle: List[List[int]]) -> int:
                row_count = len(triangle)
                dp = [[0] * row_count for _ in range(row_count)]
                dp[0][0] = triangle[0][0]
        
                for row in range(1, row_count):
                    dp[row][0] = triangle[row][0] + dp[row-1][0]
                    dp[row][row] = triangle[row][row] + dp[row-1][row-1]
        
                    for column in range(1, row):
                        dp[row][column] = triangle[row][column] + min(
                            dp[row-1][column], dp[row-1][column-1]
                        )
        
                return min(dp[-1])
        

        4.7.1371 - 2023-08-08 19:34:48 +0300 MSK

        Triangle

        Code

        class Solution:
            def minimumTotal(self, triangle: List[List[int]]) -> int:
                row_count = len(triangle)
        
        
                @cache
                def dp(row: int, column: int) -> int:
                    if row == row_count or column == row + 1:
                        return 0
                
                    return triangle[row][column] + min(dp(row + 1, column), dp(row + 1, column + 1))
        
                return dp(0, 0)
        

        4.7.1372 - 2023-08-08 14:36:45 +0300 MSK

        Kth Largest Element in an Array

        Code

        class Solution:
            def findKthLargest(self, nums, k):
                heap = []
                for num in nums:
                    heapq.heappush(heap, num)
                    if len(heap) > k:
                        heapq.heappop(heap)
                
                return heap[0]
        

        4.7.1373 - 2023-08-08 13:55:40 +0300 MSK

        Search in Rotated Sorted Array

        Code

        class Solution:
            def search(self, nums: List[int], target: int) -> int:
                nums_count = len(nums)
                left, right = 0, len(nums) - 1
        
                first_num, last_num = nums[0], nums[-1]
                if first_num == target:
                    return 0
                if last_num == target:
                    return nums_count - 1
                
                # Find the index of the pivot element (the smallest element)
                while left <= right:
                    mid = left + (right - left) // 2
                    if nums[mid] > last_num:
                        left = mid + 1
                    else:
                        right = mid - 1
                
                pivot_num = nums[left]
                if pivot_num == target:
                    return left
                
                if pivot_num < target < last_num:
                    right = nums_count - 1
                else:
                    left = 0
                
                while left <= right:
                    mid = left + (right - left) // 2
                    mid_num = nums[mid]
                    if mid_num == target:
                        return mid
                    elif mid_num > target:
                        right = mid - 1
                    else:
                        left = mid + 1
                
                return -1
        

        4.7.1374 - 2023-08-08 13:55:01 +0300 MSK

        Search in Rotated Sorted Array

        Code

        class Solution:
            def search(self, nums: List[int], target: int) -> int:
                nums_count = len(nums)
                left, right = 0, len(nums) - 1
        
                first_num, last_num = nums[0], nums[-1]
                if first_num == target:
                    return 0
                if last_num == target:
                    return nums_count - 1
                
                # Find the index of the pivot element (the smallest element)
                while left <= right:
                    mid = left + (right - left) // 2
                    if nums[mid] > last_num:
                        left = mid + 1
                    else:
                        right = mid - 1
                
                pivot_num = nums[left]
                if pivot_num == target:
                    return left
                
                if pivot_num < target < last_num:
                    right = nums_count - 1
                else:
                    left = 0
                
                while left <= right:
                    mid = (left + right) // 2
                    mid_num = nums[mid]
                    if mid_num == target:
                        return mid
                    elif mid_num > target:
                        right = mid - 1
                    else:
                        left = mid + 1
                
                return -1
        

        4.7.1375 - 2023-08-07 17:24:07 +0300 MSK

        Longest Increasing Subsequence

        Code

        class Solution:
            def lengthOfLIS(self, nums: List[int]) -> int:
                nums_count = len(nums)
                dp = [0] * nums_count
                dp[0] = 1
                for i in range(1, nums_count):
                    length = 0
                    start = nums[i]
        
                    for j in range(0, i):
                        if start > nums[j]:
                            length = max(length, dp[j])
        
                    dp[i] = 1 + length
                    
                return max(dp)
        

        4.7.1376 - 2023-08-07 14:39:05 +0300 MSK

        Coin Change

        Code

        class Solution:
            def coinChange(self, coins: List[int], amount: int) -> int:
                dp = [amount + 1] * (amount + 1)
                dp[0] = 0
        
                for current_amount in range(1, amount + 1):
                    for coin in coins:
                        diff = current_amount - coin
                        if diff < 0:
                            continue
                        
                        dp[current_amount] = min(dp[current_amount], dp[diff] + 1)
        
                return dp[-1] if dp[-1] != amount + 1 else -1
        

        4.7.1377 - 2023-08-07 14:27:07 +0300 MSK

        Coin Change

        Code

        class Solution:
            def coinChange(self, coins: List[int], amount: int) -> int:
                if amount == 0:
                    return 0
                
                @cache
                def dp(coins_value: int) -> int:
                    if coins_value == amount:
                        return 0
                    
                    if coins_value > amount:
                        return -1
                    
                    min_coins_count = -1
        
                    for coin in coins:
                        new_count = 1 + dp(coin + coins_value)
                        if new_count == 0:
                            continue
                        
                        if min_coins_count == -1 or new_count < min_coins_count:
                            min_coins_count = new_count
                    
                    return min_coins_count
        
                return dp(0)
        

        4.7.1378 - 2023-08-07 13:27:10 +0300 MSK

        Word Break

        Code

        class Solution:
            def wordBreak(self, s: str, wordDict: List[str]) -> bool:
                n = len(s)
                words = set(wordDict)
                dp = [False] * (n + 1)
                dp[0] = True
                
                for i in range(1, n + 1):
                    for j in range(i):
                        if dp[j] and s[j:i] in words:
                            dp[i] = True
                            break
                
                return dp[-1]
        

        4.7.1379 - 2023-08-07 13:25:04 +0300 MSK

        Word Break

        Code

        class Solution:
            def wordBreak(self, s: str, wordDict: List[str]) -> bool:
                @cache
                def dp(i):
                    if i < 0: 
                        return True
        
                    for word in wordDict:
                        if s[i - len(word) + 1:i + 1] == word and dp(i - len(word)):
                            return True
                    
                    return False
                
                return dp(len(s) - 1)
        

        4.7.1380 - 2023-08-07 13:10:04 +0300 MSK

        House Robber

        Code

        class Solution:
            def rob(self, nums: List[int]) -> int:
                house_count = len(nums)
        
                prev_1, prev_2 = 0, 0
        
                for house in range(0, house_count):
                    prev_1, prev_2 = max(prev_2 + nums[house], prev_1), prev_1
        
                return prev_1
        

        4.7.1381 - 2023-08-07 13:07:20 +0300 MSK

        House Robber

        Code

        class Solution:
            def rob(self, nums: List[int]) -> int:
                house_count = len(nums)
        
                dp = [0 for _ in range(house_count + 1)]
                dp[1] = nums[0]
        
                for house in range(1, house_count):
                    dp[house+1] = max(dp[house-1] + nums[house], dp[house])
        
                return dp[-1]
        

        4.7.1382 - 2023-08-07 12:57:18 +0300 MSK

        House Robber

        Code

        class Solution:
            def rob(self, nums: List[int]) -> int:
                house_count = len(nums)
                
                @cache
                def dp(house: int) -> int:
                    if house >= house_count:
                        return 0
        
                    return max(dp(house + 1), nums[house] + dp(house + 2)) 
        
                return dp(0)
        

        4.7.1383 - 2023-08-07 12:49:57 +0300 MSK

        Climbing Stairs

        Code

        class Solution:
            def climbStairs(self, n: int) -> int:
                if n < 3:
                    return n
        
                minus_one, minus_two = 2, 1
                for step in range(3, n + 1):
                    minus_one, minus_two = minus_one + minus_two, minus_one
                
                return minus_one
        

        4.7.1384 - 2023-08-07 12:45:54 +0300 MSK

        Climbing Stairs

        Code

        class Solution:
            def climbStairs(self, n: int) -> int:
        
                @cache
                def dp(step: int) -> int:
                    if step <= 2:
                        return step
                    
                    return dp(step - 1) + dp(step - 2) 
         
                return dp(n)
        

        4.7.1385 - 2023-08-07 12:17:58 +0300 MSK

        Search a 2D Matrix

        Code

        class Solution:
            def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
                length_vertical, length_horizontal = len(matrix), len(matrix[0])
        
        
                left, right = 0, length_vertical - 1
                while left <= right:
                    mid = left + (right - left) // 2
                    mid_number = matrix[mid][0]
                    
                    if mid_number == target:
                        return True
                    
                    if mid_number > target:
                        right = mid - 1
                    else:
                        left = mid + 1
                
                vertical_index = right
                left, right = 0, length_horizontal - 1
                while left <= right:
                    mid = left + (right - left) // 2
                    mid_number = matrix[vertical_index][mid]
        
                    if mid_number == target:
                        return True
                    
                    if mid_number > target:
                        right = mid - 1
                    else:
                        left = mid + 1
                    
                return False
        

        4.7.1386 - 2023-08-06 18:05:41 +0300 MSK

        Faulty Keyboard

        Code

        class Solution:
            def finalString(self, s: str) -> str:
                result = []
                for char in s:
                    if char == "i":
                        result.reverse()
                    else:
                        result.append(char)
                
                return "".join(result)
        

        4.7.1387 - 2023-08-06 18:00:12 +0300 MSK

        Maximum Number of Events That Can Be Attended II

        Code

        class Solution:
            def maxValue(self, events: List[List[int]], k: int) -> int:        
                events.sort()
                n = len(events)
                starts = [start for start, end, value in events]
                dp = [[-1] * n for _ in range(k + 1)]
                
                def dfs(cur_index, count):
                    if count == 0 or cur_index == n:
                        return 0
                    if dp[count][cur_index] != -1:
                        return dp[count][cur_index]
        
                    # Find the nearest available event after attending event 0.
        
                    next_index = bisect_right(starts, events[cur_index][1])
                    dp[count][cur_index] = max(dfs(cur_index + 1, count), events[cur_index][2] + dfs(next_index, count - 1))
                    return dp[count][cur_index]
                
                return dfs(0, k)
        

        4.7.1388 - 2023-08-06 17:37:57 +0300 MSK

        Number of Music Playlists

        Code

        class Solution:
            def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:
                MOD = 10**9 + 7
        
                # Initialize the DP table
                dp = [[0 for _ in range(n + 1)] for _ in range(goal + 1)]
                dp[0][0] = 1
        
                for i in range(1, goal + 1):
                    for j in range(1, min(i, n) + 1):
                        # The i-th song is a new song
                        dp[i][j] = dp[i - 1][j - 1] * (n - j + 1) % MOD
                        # The i-th song is a song we have played before
                        if j > k:
                            dp[i][j] = (dp[i][j] + dp[i - 1][j] * (j - k)) % MOD
        
                return dp[goal][n]
        

        4.7.1389 - 2023-08-06 17:18:41 +0300 MSK

        Smallest Sufficient Team

        Code

        class Solution:
            def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:
                req_skills_count = len(req_skills)
                skill_to_people = defaultdict(set)
                for i, person in enumerate(people):
                    for skill in person:
                        skill_to_people[skill].add(i)
        
                current = set()
                
                def backtrack(skill: int) -> Tuple[int]:
                    if skill == req_skills_count:
                        return tuple(current)
                    
                    suff_team = None
                    people_with_skill = skill_to_people[req_skills[skill]] 
                    
                    if current & people_with_skill:
                        return backtrack(skill + 1)
                
                    for person in people_with_skill:
                        current.add(person)
                        new_team = backtrack(skill + 1)
                        current.remove(person)
        
                        if suff_team is None or len(new_team) < len(suff_team):
                            suff_team = new_team
        
                    return suff_team
        
                return backtrack(0)
                
        

        4.7.1390 - 2023-08-05 17:53:24 +0300 MSK

        Insert Greatest Common Divisors in Linked List

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]:
                root = head
                
                while head and head.next:
                    next = head.next
                    new_node = ListNode(math.gcd(head.val, head.next.val), next)
                    head.next = new_node
                    head = next
                
                return root
        

        4.7.1391 - 2023-08-05 17:40:38 +0300 MSK

        Account Balance After Rounded Purchase

        Code

        class Solution:
            def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int:
                remainder = purchaseAmount % 10
                if remainder == 0:
                    return 100 - purchaseAmount
        
                if remainder >= 5:
                    return 100 - ((purchaseAmount // 10) + 1) * 10 
                
                return 100 - (purchaseAmount // 10) * 10
        

        4.7.1392 - 2023-08-05 12:39:41 +0300 MSK

        Unique Binary Search Trees II

        Code

        class Solution:
            def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
                @cache
                def generate_trees(l, r):
                    return [None] if l > r else [
                        TreeNode(val, left, right)
                        for val in range(l, r + 1)
                        for left in generate_trees(l, val - 1)
                        for right in generate_trees(val + 1, r)
                    ]
                
                return generate_trees(1, n)
        

        4.7.1393 - 2023-08-04 19:40:16 +0300 MSK

        Maximum Number of Achievable Transfer Requests

        Code

        class Solution:
            def maximumRequests(self, n, requests):
                current = [0] * n
                length = len(requests)
                
                def backtrack(req_index: int, count: int) -> int:
                    if req_index == length:
                        return 0 if any(current) else count
        
                    req_from, req_to = requests[req_index]
                    
                    current[req_from] -= 1
                    current[req_to] += 1
                    take = backtrack(req_index + 1, count + 1)
        
                    current[req_from] += 1
                    current[req_to] -= 1
                    non_take = backtrack(req_index + 1, count)
                    
                    return max(take, non_take)
                
                return backtrack(0, 0)
        

        4.7.1394 - 2023-08-04 19:38:00 +0300 MSK

        Word Break

        Code

        class Solution:
            def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        
                @cache
                def calculate(i: int) -> bool:
                    if i < 0:
                        return True
                    
                    for word in wordDict:
                        length = len(word)
                        if s[i-length+1:i+1] == word and calculate(i-length):
                            return True
                    
                    return False
        
                return calculate(len(s) - 1)
                
        

        4.7.1395 - 2023-08-04 19:37:15 +0300 MSK

        Word Break

        Code

        class Solution:
            def wordBreak(self, s: str, wordDict: List[str]) -> bool:
                words = set(wordDict)
            
                @cache
                def calculate(i: int) -> bool:
                    if i < 0:
                        return True
                    
                    for word in wordDict:
                        length = len(word)
                        if s[i-length+1:i+1] == word and calculate(i-length):
                            return True
                    
                    return False
        
                return calculate(len(s) - 1)
                
        

        4.7.1396 - 2023-08-03 12:33:31 +0300 MSK

        Letter Combinations of a Phone Number

        Code

        class Solution:
            def letterCombinations(self, digits: str) -> List[str]:
                length = len(digits)
                if length == 0:
                    return []
        
                digit_map: Dict[int, str] = {
                    "1": [],
                    "2": ["a", "b", "c"],
                    "3": ["d", "e", "f"],
                    "4": ["g", "h", "i"],
                    "5": ["j", "k", "l"],
                    "6": ["m", "n", "o"],
                    "7": ["p", "q", "r", "s"],
                    "8": ["t", "u", "v"],
                    "9": ["w", "x", "y", "z"],
                    "0": [" "]
                }
        
                current = []
                
                def backtrack(digit: int) -> Generator[None, None, str]:
                    if digit == length:
                        yield "".join(current[:])
                        return
                    
                    for char in digit_map[digits[digit]]:
                        current.append(char)
                        yield from backtrack(digit + 1)
                        current.pop()
        
                return tuple(combination for combination in backtrack(0))
        

        4.7.1397 - 2023-08-03 12:32:00 +0300 MSK

        Letter Combinations of a Phone Number

        Code

        class Solution:
            def letterCombinations(self, digits: str) -> List[str]:
                length = len(digits)
                if length == 0:
                    return []
        
                digit_map: Dict[int, str] = {
                    "1": [],
                    "2": ["a", "b", "c"],
                    "3": ["d", "e", "f"],
                    "4": ["g", "h", "i"],
                    "5": ["j", "k", "l"],
                    "6": ["m", "n", "o"],
                    "7": ["p", "q", "r", "s"],
                    "8": ["t", "u", "v"],
                    "9": ["w", "x", "y", "z"],
                    "0": [" "]
                }
        
                current = []
                
                def backtrack(digit: int) -> Generator[None, None, str]:
                    if digit == length:
                        yield "".join(current[:])
                        return
                    
                    for char in digit_map[digits[digit]]:
                        current.append(char)
                        yield from backtrack(digit + 1)
                        current.pop()
        
                return tuple(combination for combination in backtrack(0))
        

        4.7.1398 - 2023-08-02 19:02:58 +0300 MSK

        Course Schedule

        Code

        class Solution:
            def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
                courses = defaultdict(set)
        
                for course, prereq in prerequisites:
                    courses[course].add(prereq)
        
                if not courses:
                    return True
                
                stack = set()
        
                @cache
                def check(course: int) -> bool:
                    if course not in courses:
                        return True
                    
                    if course in stack:
                        return False
        
                    prereqs = courses[course]
        
                    if prereqs & stack:
                        return False
        
                    stack.add(course)
        
                    for prereq in prereqs:
                        if not check(prereq):
                            return False
            
                    stack.remove(course)
                    
                    return True
        
                for course in courses:
                    if not check(course):
                        return False
        
                return True
        

        4.7.1399 - 2023-08-02 18:11:45 +0300 MSK

        Find Eventual Safe States

        Code

        class Solution:
            def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
                length = len(graph)
                indegree = [0] * length
                adj = [[] for _ in range(length)]
        
                for i in range(length):
                    for edge in graph[i]:
                        adj[edge].append(i)
                        indegree[i] += 1
        
                q = deque()
                # Push all the nodes with indegree zero in the queue.
                for i in range(length):
                    if indegree[i] == 0:
                        q.append(i)
        
                safe = [False] * length
                while q:
                    node = q.popleft()
                    safe[node] = True
        
                    for neighbor in adj[node]:
                        # Delete the edge "node -> neighbor".
                        indegree[neighbor] -= 1
                        if indegree[neighbor] == 0:
                            q.append(neighbor)
        
                safe_nodes = []
                for i in range(length):
                    if safe[i]:
                        safe_nodes.append(i)
        
                return safe_nodes
        

        4.7.1400 - 2023-08-02 17:33:24 +0300 MSK

        Maximize the Confusion of an Exam

        Code

        class Solution:
            def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
                length = len(answerKey)
                char_t, char_f = "T", "F"
                max_size = k
                count = defaultdict(int)
                
                for char in answerKey[:k]:
                    count[char] += 1
        
                left = 0
                for right in range(k, length):
                    count[answerKey[right]] += 1
                    
                    while min(count[char_t], count[char_f]) > k: 
                        count[answerKey[left]] -= 1
                        left += 1
                    
                    size = right - left + 1
                    if size > max_size:
                        max_size = size
                            
                return max_size
        
        
        
                
        

        4.7.1401 - 2023-08-02 11:09:23 +0300 MSK

        Minimum Size Subarray Sum

        Code

        class Solution:
            def minSubArrayLen(self, target: int, nums: List[int]) -> int:
                left = 0
                sum_of_subarray = 0
                min_length = float('inf')
                
                for right in range(len(nums)):
                    sum_of_subarray += nums[right]
                    
                    while sum_of_subarray >= target:
                        min_length = min(min_length, right - left + 1)
                        sum_of_subarray -= nums[left]
                        left += 1
        
                if min_length == float('inf'):
                    return 0
        
                return min_length
        

        4.7.1402 - 2023-08-02 11:07:07 +0300 MSK

        Single Number II

        Code

        class Solution:
            def singleNumber(self, nums: List[int]) -> int:
                nums.sort()
                length = len(nums)
                for i in range(0, length, 3):
                    if i == length - 1:
                        return nums[i]
            
                    num_1, num_2, num_3 = nums[i], nums[i+1], nums[i+2]
        
                    if num_1 == num_2 == num_3:
                        continue
                    
                    if num_2 == num_3:
                        return num_1
                    
                    if num_1 == num_3:
                        return num_2
                    
                    return num_3
                    
        

        4.7.1403 - 2023-08-02 11:00:07 +0300 MSK

        Buddy Strings

        Code

        class Solution:
            def buddyStrings(self, s: str, goal: str) -> bool:
                length_1, length_2 = len(s), len(goal)
        
                if length_1 != length_2:
                    return False
                
                if s == goal:
                    freq = defaultdict(int)
                    for char in s:
                        freq[char] += 1
                        if freq[char] == 2:
                            return True
                    return False
                
                swap_1, swap_2 = -1, -1
                
                for i in range(length_1):
                    char_1, char_2 = s[i], goal[i]
                    
                    if char_1 == char_2:
                        continue
                    
                    if swap_1 == -1:
                        swap_1 = i
                    elif swap_2 == -1:
                        swap_2 = i
                    else:
                        return False
                    
        
                return swap_2 != -1 and s[swap_1] == goal[swap_2] and s[swap_2] == goal[swap_1]
        

        4.7.1404 - 2023-08-02 10:39:16 +0300 MSK

        Generate Parentheses

        Code

        class Solution:
            def generateParenthesis(self, n: int) -> List[str]:
        
                current = []
                current_max = n * 2
                chars = "()"
        
        
                def backtrack(open: int, closed: int) -> Generator[None, None, List[str]]:
                    if len(current) == current_max:
                        yield "".join(current)
                    
                    if open:
                        current.append(chars[0])
                        yield from backtrack(open - 1, closed)
                        current.pop()
                    
                    if closed and closed > open:
                        current.append(chars[1])
                        yield from backtrack(open, closed - 1)
                        current.pop()
                
                return tuple(combination for combination in backtrack(n, n))
        

        4.7.1405 - 2023-08-02 10:26:02 +0300 MSK

        Permutations

        Code

        class Solution:
            def permute(self, nums: List[int]) -> List[List[int]]:
        
                length = len(nums)
                current = []
                current_contains = [False] * length
        
                def backtrack() -> Generator[None, None, List[int]]:
                    if len(current) == length:
                        yield tuple(current[:])
                        return
        
                    for i in range(length):
                        if current_contains[i]:
                            continue
        
                        current_contains[i] = True
                        current.append(nums[i])
        
                        yield from backtrack()
        
                        current_contains[i] = False
                        current.pop()
                    
                    return
        
                return tuple(combination for combination in backtrack()) 
        

        4.7.1406 - 2023-08-01 20:38:09 +0300 MSK

        Maximum Number of Achievable Transfer Requests

        Code

        class Solution:
            def maximumRequests(self, n, requests):
                current = [0] * n
                length = len(requests)
                
                def backtrack(req_index: int, count: int) -> int:
                    if req_index == length:
                        return 0 if any(current) else count
        
                    req_from, req_to = requests[req_index]
                    
                    current[req_from] -= 1
                    current[req_to] += 1
                    take = backtrack(req_index + 1, count + 1)
        
                    current[req_from] += 1
                    current[req_to] -= 1
                    non_take = backtrack(req_index + 1, count)
                    
                    return max(take, non_take)
                
                return backtrack(0, 0)
        

        4.7.1407 - 2023-08-01 20:19:26 +0300 MSK

        Maximum Number of Achievable Transfer Requests

        Code

        class Solution:
            def __init__(self):
                self.ans = 0
        
            def helper(self, start, requests, indegree, n, count):
                if start == len(requests):
                    for i in range(n):
                        if indegree[i] != 0:
                            return
                    self.ans = max(self.ans, count)
                    return
        
                # Take 
                indegree[requests[start][0]] -= 1
                indegree[requests[start][1]] += 1
                self.helper(start + 1, requests, indegree, n, count + 1)
        
                # Not-take
                indegree[requests[start][0]] += 1
                indegree[requests[start][1]] -= 1
                self.helper(start + 1, requests, indegree, n, count)
        
            def maximumRequests(self, n, requests):
                indegree = [0] * n
                self.helper(0, requests, indegree, n, 0)
                return self.ans
        

        4.7.1408 - 2023-08-01 18:39:03 +0300 MSK

        Count Complete Subarrays in an Array

        Code

        class Solution:
            def countCompleteSubarrays(self, nums: List[int]) -> int:
                length = len(nums)
                elems_count = len(set(nums))
                
                if elems_count == length:
                    return 1
                
                if elems_count == 1:
                    return length + sum(i for i in range(1, length))
                
                result, elems, min_j = 0, defaultdict(int), 0
                for i in range(length):
                    left = nums[i]
                    
                    for j in range(min_j, length):
                        right = nums[j]
                        elems[right] += 1
                        
                        if len(elems) != elems_count:
                            continue
                        
                        if elems[right] == 1:
                            elems.pop(right)
                        else:
                            elems[right] -= 1 
            
                        result += length - j
                        min_j = j
                        break
                    else:
                        return result
                    
                    if elems[left] == 1:
                        elems.pop(left)
                    else:
                        elems[left] -= 1
                            
                return result
        

        4.7.1409 - 2023-08-01 17:52:16 +0300 MSK

        Number of Employees Who Met the Target

        Code

        class Solution:
            def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
                count = 0
                for hour in hours:
                    if hour < target:
                        continue
                    count += 1
                
                return count
        

        4.7.1410 - 2023-08-01 17:35:47 +0300 MSK

        Combinations

        Code

        class Solution:
            def combine(self, n: int, k: int) -> List[List[int]]:
                current = []
                
                def backtrack(first: int) -> Generator[None, None, List[int]]:
                    if len(current) == k:
                        yield tuple(current[:])
                        return
        
                    for i in range(first, n + 1):
                        current.append(i)
                        yield from backtrack(i + 1)
                        current.pop()
                    
                    return
        
                return tuple(combination for combination in backtrack(1)) 
        

        4.7.1411 - 2023-08-01 17:33:23 +0300 MSK

        Combinations

        Code

        class Solution:
            def combine(self, n: int, k: int) -> List[List[int]]:
                current, result = [], []
                
                def backtrack(first: int) -> None:
                    if len(current) == k:
                        result.append(tuple(current[:]))
                        return
        
                    for i in range(first, n + 1):
                        current.append(i)
                        backtrack(i + 1)
                        current.pop()
                    
                    return
        
                backtrack(1)
        
                return result 
        

        4.7.1412 - 2023-08-01 17:14:55 +0300 MSK

        Combinations

        Code

        class Solution:
            def combine(self, n: int, k: int) -> List[List[int]]:
                def generate_combinations(elems: List[int], num: int):
                    total = len(elems)
                    if num > total:
                        return
                    curr_indices = list(range(num))
                    reversed_num = tuple(reversed(range(num)))
        
                    while True:
                        yield list(elems[i] for i in curr_indices)
                        
                        for idx in reversed_num:
                            if curr_indices[idx] != idx + total - num:
                                break
                        else:
                            return
        
                        curr_indices[idx] += 1
                        for j in range(idx+1, num):
                            curr_indices[j] = curr_indices[j-1] + 1
        
                return [combination for combination in generate_combinations(tuple(range(1, n+1)), k)]
        

        4.7.1413 - 2023-07-31 19:28:12 +0300 MSK

        Container With Most Water

        Code

        class Solution:
            def maxArea(self, height: List[int]) -> int:
                left = 0
                right = len(height) - 1
                maxArea = 0
        
                while left < right:
                    currentArea = min(height[left], height[right]) * (right - left)
                    if currentArea > maxArea:
                        maxArea = currentArea
        
                    if height[left] < height[right]:
                        left += 1
                    else:
                        right -= 1
        
                return maxArea
        

        4.7.1414 - 2023-07-31 17:17:46 +0300 MSK

        Longest Palindromic Substring

        Code

        class Solution:
            def longestPalindrome(self, s: str) -> str:
                n = len(s)
                dp = [[False] * n for _ in range(n)]
                ans = [0, 0]
                
                for i in range(n):
                    dp[i][i] = True
                
                for i in range(n - 1):
                    if s[i] == s[i + 1]:
                        dp[i][i + 1] = True
                        ans = [i, i + 1]
        
                for diff in range(2, n):
                    for i in range(n - diff):
                        j = i + diff
                        if s[i] == s[j] and dp[i + 1][j - 1]:
                            dp[i][j] = True
                            ans = [i, j]
        
                i, j = ans
                return s[i:j + 1]
        

        4.7.1415 - 2023-07-31 14:46:40 +0300 MSK

        Minimum ASCII Delete Sum for Two Strings

        Code

        class Solution:
            def minimumDeleteSum(self, s1: str, s2: str) -> int:
                length_1, length_2 = len(s1), len(s2)
        
                @cache
                def calculate(i: int, j: int) -> int:    
                    if i >= length_1 and j >= length_2:
                        return 0
                    
                    if i >= length_1:
                        return sum(ord(char) for char in s2[j:])
                    
                    if j >= length_2:
                        return sum(ord(char) for char in s1[i:])
                    
                    if s1[i] == s2[j]:
                        return calculate(i + 1, j + 1)
                    
                    return min(
                        ord(s1[i]) + calculate(i + 1, j),
                        ord(s2[j]) + calculate(i, j + 1)
                    )
        
                return calculate(0, 0)
        

        4.7.1416 - 2023-07-30 20:11:15 +0300 MSK

        Strange Printer

        Code

        class Solution:
            def strangePrinter(self, s: str) -> int:
                n = len(s)
                dp = [[n] * n for _ in range(n)]
                for length in range(1, n + 1):
                    for left in range(n - length + 1):
                        right = left + length - 1
                        j = -1
                        for i in range(left, right):
                            if s[i] != s[right] and j == -1:
                                j = i
                            if j != -1:
                                dp[left][right] = min(dp[left][right], 1 + dp[j][i] + dp[i + 1][right])
                
                        if j == -1:
                            dp[left][right] = 0
        
                return dp[0][n - 1] + 1
        

        4.7.1417 - 2023-07-30 10:12:02 +0300 MSK

        Predict the Winner

        Code

        class Solution:
            def PredictTheWinner(self, nums: List[int]) -> bool:
                length = len(nums)
                is_even = length % 2 == 0
        
                if length < 3:
                    return True
                
                @cache
                def max_diff(left: int, right: int) -> int:
                    left_num, right_num = nums[left], nums[right]
                    
                    if left == right:
                        return left_num
                    
                    score_by_left = left_num - max_diff(left + 1, right)
                    score_by_right = right_num - max_diff(left, right - 1)
                    return max(score_by_left, score_by_right)
        
                return max_diff(0, length - 1) >= 0
        

        4.7.1418 - 2023-07-29 18:54:20 +0300 MSK

        Predict the Winner

        Code

        class Solution:
            def PredictTheWinner(self, nums: List[int]) -> bool:
                length = len(nums)
                is_even = length % 2 == 0
        
                if length < 3:
                    return True
                
                @cache
                def max_diff(left: int, right: int) -> int:
                    left_num, right_num = nums[left], nums[right]
                    
                    if left == right:
                        return left_num
                    
                    score_by_left = left_num - max_diff(left + 1, right)
                    score_by_right = right_num - max_diff(left, right - 1)
                    return max(score_by_left, score_by_right)
        
                return max_diff(0, length - 1) >= 0
        

        4.7.1419 - 2023-07-29 18:51:41 +0300 MSK

        Predict the Winner

        Code

        class Solution:
            def PredictTheWinner(self, nums: List[int]) -> bool:
                length = len(nums)
                is_even = length % 2 == 0
        
                if length < 3:
                    return True
                
                def max_diff(left: int, right: int) -> int:
                    left_num, right_num = nums[left], nums[right]
                    
                    if left == right:
                        return left_num
                    
                    score_by_left = left_num - max_diff(left + 1, right)
                    score_by_right = right_num - max_diff(left, right - 1)
                    return max(score_by_left, score_by_right)
        
                return max_diff(0, length - 1) >= 0
        

        4.7.1420 - 2023-07-29 13:24:33 +0300 MSK

        Soup Servings

        Code

        class Solution:
            def soupServings(self, n: int) -> float:
                servings = ceil(n / 25)
        
                states = defaultdict(dict)
                moves = [[-4, 0], [-3, -1], [-2, -2], [-1, -3]]
            
                @cache
                def calculate(soup_a: int, soup_b: int) -> float:
                    if soup_a <= 0 and soup_b <= 0:
                        return 0.5
                    if soup_a <= 0:
                        return 1.0
                    if soup_b <= 0:
                        return 0.0
                    if soup_a in states and soup_b in states[soup_a]:
                        return states[soup_a][soup_b]
                    
                    state = sum(calculate(soup_a + move[0], soup_b + move[1]) for move in moves) / 4.0
                    states[soup_a][soup_b] = state
        
                    return state
        
                max_probability = 1 - 1e-5
        
                for serving in range(1, servings + 1):
                    state = calculate(serving, serving)
                    if state > max_probability:
                        return 1.0
                
                return calculate(servings, servings)
               
        

        4.7.1421 - 2023-07-27 11:41:11 +0300 MSK

        Fair Distribution of Cookies

        Code

        class Solution:
            def distributeCookies(self, cookies: List[int], k: int) -> int:
                cur = [0] * k
                n = len(cookies)
        
                def dfs(i, zero_count):
                    # If there are not enough cookies remaining, return `float('inf')` 
                    # as it leads to an invalid distribution.
                    if n - i < zero_count:
                        return float('inf')
                    
                    # After distributing all cookies, return the unfairness of this
                    # distribution.
                    if i == n:
                        return max(cur)
                    
                    # Try to distribute the i-th cookie to each child, and update answer
                    # as the minimum unfairness in these distributions.
                    answer = float('inf')
                    for j in range(k):
                        zero_count -= int(cur[j] == 0)
                        cur[j] += cookies[i]
                        
                        # Recursively distribute the next cookie.
                        answer = min(answer, dfs(i + 1, zero_count))
                        
                        cur[j] -= cookies[i]
                        zero_count += int(cur[j] == 0)
                    
                    return answer
                
                return dfs(0, k)
        

        4.7.1422 - 2023-07-27 11:39:36 +0300 MSK

        Fair Distribution of Cookies

        Code

        class Solution:
            def distributeCookies(self, cookies: List[int], k: int) -> int:
                cur = [0] * k
                n = len(cookies)
        
                def dfs(i, zero_count):
                    # If there are not enough cookies remaining, return `float('inf')` 
                    # as it leads to an invalid distribution.
                    if n - i < zero_count:
                        return float('inf')
                    
                    # After distributing all cookies, return the unfairness of this
                    # distribution.
                    if i == n:
                        return max(cur)
                    
                    # Try to distribute the i-th cookie to each child, and update answer
                    # as the minimum unfairness in these distributions.
                    answer = float('inf')
                    for j in range(k):
                        zero_count -= int(cur[j] == 0)
                        cur[j] += cookies[i]
                        
                        # Recursively distribute the next cookie.
                        answer = min(answer, dfs(i + 1, zero_count))
                        
                        cur[j] -= cookies[i]
                        zero_count += int(cur[j] == 0)
                    
                    return answer
                
                return dfs(0, k)
        

        4.7.1423 - 2023-07-27 11:28:33 +0300 MSK

        Maximum Running Time of N Computers

        Code

        class Solution:
            # n = 2, batteries = [3,3,3], Output: 4
            # n = 2, batteries = [1,1,1,1], Output: 2
            def maxRunTime(self, n: int, batteries: List[int]) -> int:
                length = len(batteries)
        
                if length < n:
                    return 0
                
                if length == n:
                    return min(batteries)
        
                batteries.sort()
                extra = sum(batteries[:-n])
                live = batteries[-n:]
        
                
                # We increase the total running time using 'extra' by increasing 
                # the running time of the computer with the smallest battery.
                for i in range(n - 1):
                    # If the target running time is between live[i] and live[i + 1].
                    if extra // (i + 1) < live[i + 1] - live[i]:
                        return live[i] + extra // (i + 1)
                    
                    # Reduce 'extra' by the total power used.
                    extra -= (i + 1) * (live[i + 1] - live[i])
                
                # If there is power left, we can increase the running time 
                # of all computers.
                return live[-1] + extra // n
        

        4.7.1424 - 2023-07-26 22:56:56 +0300 MSK

        Minimum Speed to Arrive on Time

        Code

        class Solution:
            def minSpeedOnTime(self, dist: List[int], hour: float) -> int:
                length = len(dist)
                if hour >= sum(dist):
                    return 1
                
                if hour <= length - 1:
                    return -1
                
                time_remaining = hour - length + 1
                max_speed = int(max(
                    max(dist), dist[-1] // time_remaining + 1
                ))
                min_speed = 1
                result = -1
                while min_speed < max_speed:
                    speed = min_speed + (max_speed - min_speed) // 2
                    time = dist[-1] / speed + sum(
                        (distance + speed - 1) // speed 
                        for distance in dist[:-1]
                    )
                    
                    if time > hour:
                        min_speed = speed + 1
                    else:
                        max_speed = speed
                
                return min_speed
        

        4.7.1425 - 2023-07-25 16:45:40 +0300 MSK

        Peak Index in a Mountain Array

        Code

        class Solution:
            # [0,3,2,1,0]
            def peakIndexInMountainArray(self, arr: List[int]) -> int:
                length = len(arr)
        
                left, right = 0, length - 1
                while left < right:
                    mid = left + (right - left) // 2
        
                    if arr[mid] < arr[mid + 1]:
                        left = mid + 1
                    else:
                        right = mid
        
                return left
                
        

        4.7.1426 - 2023-07-25 16:38:25 +0300 MSK

        Peak Index in a Mountain Array

        Code

        class Solution:
            # [0,3,2,1,0]
            def peakIndexInMountainArray(self, arr: List[int]) -> int:
                length = len(arr)
        
                left, right = 0, length - 1
                while left <= right:
                    peak = left + (right - left) // 2
                    left_val, right_val = arr[peak-1], arr[peak+1]
                    peak_val = arr[peak]
        
                    if left_val < peak_val > right_val:
                        return peak
                    
                    if right_val > peak_val:
                        left = peak + 1
                    else:
                        right = peak - 1
                
                return left
                
        

        4.7.1427 - 2023-07-24 21:17:10 +0300 MSK

        Longest Substring Without Repeating Characters

        Code

        class Solution:
            def lengthOfLongestSubstring(self, s: str) -> int:
                length = len(s)
                if length < 2:
                    return length
                
                max_length, left, charset = 1, 0, set([s[0]])
                for right in range(1, length):
                    letter = s[right]
                    if letter not in charset:
                        charset.add(letter)
                        continue
        
                    this_length = right - left
                    if this_length > max_length:
                        max_length = this_length
                    
                    while letter in charset:
                        charset.remove(s[left])
                        left += 1
                    
                    charset.add(letter)
        
                return max(max_length, length - left)
        

        4.7.1428 - 2023-07-24 21:04:18 +0300 MSK

        Longest Substring Without Repeating Characters

        Code

        class Solution:
            def lengthOfLongestSubstring(self, s: str) -> int:
                length = len(s)
                if length < 2:
                    return length
                
                max_length = 0
                start = 0
                indexes = {s[0]: 0}
                for end in range(1, length):
                    letter = s[end]
                    if letter not in indexes:
                        indexes[letter] = end
                        continue
        
                    this_length = end - start
                    if this_length > max_length:
                        max_length = this_length
                    
                    letter_index = indexes[letter]
                    
                    for remove_letter in s[start:letter_index]:
                        indexes.pop(remove_letter)
        
                    indexes[letter], start = end, letter_index + 1
        
                return max(max_length, length - start)
        

        4.7.1429 - 2023-07-24 20:07:58 +0300 MSK

        Construct the Rectangle

        Code

        class Solution:
            def constructRectangle(self, area: int) -> List[int]:
                return next([area//width, width] 
                            for width in range(int(area**0.5), 0, -1) 
                            if area % width == 0)
        

        4.7.1430 - 2023-07-24 19:52:59 +0300 MSK

        Max Consecutive Ones

        Code

        class Solution:
            def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
                max_count, count = 0, 0
                for number in nums:
                    if not number:
                        max_count = max(max_count, count)
                        count = 0
                        continue
                    
                    count += 1
                
                return max(max_count, count)
        

        4.7.1431 - 2023-07-24 19:34:48 +0300 MSK

        License Key Formatting

        Code

        class Solution:
            def licenseKeyFormatting(self, s: str, k: int) -> str:
                result = []
                count = 0
                for letter in reversed(s):
                    if letter == "-":
                        continue
        
                    if count == k:
                        result.append("-")
                        count = 0
                    
                    count += 1
                    result.append(letter.upper())
        
                return "".join(reversed(result))
        

        4.7.1432 - 2023-07-24 19:02:15 +0300 MSK

        License Key Formatting

        Code

        class Solution:
            # "5F3Z-2e-9-w" -> "5F3Z2E9W" -> "5F3Z2E9W"
            def licenseKeyFormatting(self, s: str, k: int) -> str:
                letters = s.replace("-", "").upper()
                result = []
                end = len(letters)
                while end > 0:
                    start = end - k
                    if start < 0:
                        start = 0
                    result.append(letters[start:end])
                    end -= k
        
                return "-".join(reversed(result))
        

        4.7.1433 - 2023-07-24 18:47:17 +0300 MSK

        Island Perimeter

        Code

        class Solution:
            def islandPerimeter(self, grid: List[List[int]]) -> int:
                perimeter = 0
                last_row = len(grid) - 1        
                last_cell = len(grid[0]) - 1
                for i, row in enumerate(grid):
                    for j, cell in enumerate(row):
                        if cell == 0:
                            continue
                        
                        if j == 0 or row[j-1] == 0:
                            perimeter += 1
                        
                        if j == last_cell or row[j+1] == 0:
                            perimeter += 1
                        
                        if i == 0 or grid[i-1][j] == 0:
                            perimeter += 1
        
                        if i == last_row or grid[i+1][j] == 0:
                            perimeter += 1
                
                return perimeter
                        
        

        4.7.1434 - 2023-07-24 16:56:56 +0300 MSK

        Intersection of Two Arrays

        Code

        class Solution:
            def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
                return set(nums1).intersection(nums2)
        

        4.7.1435 - 2023-07-24 16:56:13 +0300 MSK

        Intersection of Two Arrays

        Code

        class Solution:
            def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
                return set(nums1) & set(nums2)
        

        4.7.1436 - 2023-07-24 16:54:39 +0300 MSK

        Find the Difference

        Code

        class Solution:
            def findTheDifference(self, s: str, t: str) -> str:
                letters = defaultdict(int)
                for letter in s:
                    letters[letter] += 1
        
                for letter in t:
                    if letters[letter] == 0:
                        return letter
                    
                    letters[letter] -= 1
                
                return None
        

        4.7.1437 - 2023-07-24 16:51:33 +0300 MSK

        First Unique Character in a String

        Code

        class Solution:
            def firstUniqChar(self, s: str) -> int:
                counts = defaultdict(int)
                repeated_index = len(s)
                for letter in s:
                    counts[letter] += 1
                
                for i, letter in enumerate(s):
                    if counts[letter] != 1:
                        continue
                    
                    return i
                
                return -1
        

        4.7.1438 - 2023-07-24 16:49:38 +0300 MSK

        First Unique Character in a String

        Code

        class Solution:
            def firstUniqChar(self, s: str) -> int:
                counts = {}
                repeated_index = len(s)
                for i, letter in enumerate(s):
                    if letter in counts:
                        counts[letter] = repeated_index
                        continue
                    
                    counts[letter] = i
                
                result = repeated_index
        
                for letter, index in counts.items():
                    if index == repeated_index:
                        continue
                    
                    if index < result:
                        result = index
        
                return result if result != repeated_index else -1
        

        4.7.1439 - 2023-07-24 16:32:14 +0300 MSK

        Sum of Left Leaves

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
                nodes = set([root])
                result = 0
        
                while nodes:
                    node = nodes.pop()
                    
                    if node.left and not node.left.left and not node.left.right:
                        result += node.left.val
                    elif node.left:
                        nodes.add(node.left)
                    
                    if node.right:
                        nodes.add(node.right)
                    
                return result
        

        4.7.1440 - 2023-07-24 16:19:40 +0300 MSK

        Longest Palindrome

        Code

        class Solution:
            def longestPalindrome(self, s: str) -> int:
                counts = defaultdict(int)
        
                for letter in s:
                    counts[letter] += 1
                
                result = sum(count if count % 2 == 0 else count - 1
                             for symbol, count in counts.items())
        
                if result < len(s):
                    result += 1
        
                return result
        

        4.7.1441 - 2023-07-24 16:17:10 +0300 MSK

        Longest Palindrome

        Code

        class Solution:
            def longestPalindrome(self, s: str) -> int:
                counts = defaultdict(int)
        
                for letter in s:
                    counts[letter] += 1
                
                result = 0
                used_odd_letter = False
                for letter, count in counts.items():
                    is_odd = count % 2 != 0 
                    if is_odd and used_odd_letter:
                        result -= 1
                    elif is_odd:
                        used_odd_letter = True
                    result += count
        
                return result
        

        4.7.1442 - 2023-07-24 13:04:29 +0300 MSK

        Third Maximum Number

        Code

        class Solution:
            def thirdMax(self, nums: List[int]) -> int:
                nums.sort(reverse=True)
                number_max = nums[0]
                count = 1
                for i in range(1, len(nums)):
                    number = nums[i]
                    if number == nums[i-1]:
                        continue
                    
                    count += 1
        
                    if count == 3:
                        return number 
                
                return number_max
        

        4.7.1443 - 2023-07-24 13:03:31 +0300 MSK

        Third Maximum Number

        Code

        class Solution:
            def thirdMax(self, nums: List[int]) -> int:
                nums.sort(reverse=True)
                number_max = nums[0]
                count = 1
                for i in range(1, len(nums)):
                    number = nums[i]
                    if number == nums[i-1]:
                        continue
                    
                    count += 1
        
                    if count == 3:
                        return number 
        
                    if number > number_max:
                        number_max = number
                
                return number_max
        

        4.7.1444 - 2023-07-24 12:58:41 +0300 MSK

        Add Strings

        Code

        class Solution:
            def addStrings(self, num1: str, num2: str) -> str:
                result = []
                index_1, index_2 = len(num1) - 1, len(num2) - 1
        
        
                carry = 0
                while index_1 >= 0 or index_2 >= 0 or carry:
                    digit_1 = num1[index_1] if index_1 >= 0 else 0
                    digit_2 = num2[index_2] if index_2 >= 0 else 0
                    digit = int(digit_1) + int(digit_2) + carry
                    if digit > 9:
                        carry = 1
                        digit %= 10
                    else:
                        carry = 0
        
                    result.append(str(digit))
                    index_1 -= 1
                    index_2 -= 1 
        
                return "".join(reversed(result))
        

        4.7.1445 - 2023-07-24 12:56:22 +0300 MSK

        Add Strings

        Code

        class Solution:
            def addStrings(self, num1: str, num2: str) -> str:
                result = []
                length_1, length_2 = len(num1), len(num2)
                index_1, index_2 = length_1 - 1, length_2 - 1
        
        
                carry = 0
                while index_1 >= 0 or index_2 >= 0 or carry:
                    digit_1 = num1[index_1] if index_1 >= 0 else 0
                    digit_2 = num2[index_2] if index_2 >= 0 else 0
                    digit = int(digit_1) + int(digit_2) + carry
                    if digit > 9:
                        carry = 1
                        digit %= 10
                    else:
                        carry = 0
        
                    result.append(str(digit))
                    index_1 -= 1
                    index_2 -= 1 
        
                return "".join(reversed(result))
        

        4.7.1446 - 2023-07-24 12:44:43 +0300 MSK

        Assign Cookies

        Code

        class Solution:
            def findContentChildren(self, g: List[int], s: List[int]) -> int:
                g.sort(reverse=True)
                s.sort(reverse=True)
                count = 0
                cookie_index = 0
                cookie_count = len(s)
                for greed in g:
                    if cookie_index >= cookie_count or greed > s[cookie_index]:
                        continue
        
                    count += 1
                    cookie_index += 1
                    
                return count
        

        4.7.1447 - 2023-07-24 12:40:04 +0300 MSK

        Assign Cookies

        Code

        class Solution:
            def findContentChildren(self, g: List[int], s: List[int]) -> int:
                greed = 0
                g.sort(reverse=True)
                s.sort(reverse=True)
                children_count = len(g)
                count = 0
                for cookie_size in s:
                    while greed < children_count and g[greed] > cookie_size:
                        greed += 1
                    
                    if greed >= children_count:
                        break
        
                    count += 1
                    greed += 1
                    
                return count
        

        4.7.1448 - 2023-07-24 11:13:00 +0300 MSK

        Pow(x, n)

        Code

        class Solution:
            def myPow(self, x: float, n: int) -> float:
                if n == 0:
                    return 1
        
                if n < 0:
                    n *= -1
                    x = 1 / x
        
                result = 1
                while n:
                    if n % 2:
                        result *= x
                        n -= 1
                    x *= x
                    n //= 2
                
                return result
        

        4.7.1449 - 2023-07-23 21:12:51 +0300 MSK

        Find All Numbers Disappeared in an Array

        Code

        class Solution:
            # [1,1,3,4], [1,2,3,4] -> [2]
            def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
                for number in nums:
                    index = abs(number) - 1
                    nums[index] = -1 * abs(nums[index])
                
                return [number
                        for number in range(1, len(nums) + 1) 
                        if nums[number-1] > 0]
                
        

        4.7.1450 - 2023-07-23 21:01:06 +0300 MSK

        Find All Numbers Disappeared in an Array

        Code

        class Solution:
            # [1,1,3,4], [1,2,3,4] -> [2]
            def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
                result = {number: True for number in range(1, len(nums) + 1)}
        
                for number in nums:
                    result[number] = False
                
                return [number for number, valid in result.items() if valid]
        

        4.7.1451 - 2023-07-23 20:55:57 +0300 MSK

        Find All Numbers Disappeared in an Array

        Code

        class Solution:
            # [1,1,3,4], [1,2,3,4] -> [2]
            def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
                nums.sort()
                result = []
                length = len(nums)
                j = 0
                for i in range(1, length + 1):
                    while j < length and nums[j] < i:
                        j += 1
                    
                    if j < length and nums[j] == i:
                        continue
        
                    result.append(i)
        
                return result
        

        4.7.1452 - 2023-07-23 20:18:00 +0300 MSK

        Arranging Coins

        Code

        class Solution:
            def arrangeCoins(self, n: int) -> int:
                left, right = 0, n
        
                while left <= right:
                    middle = left + (right - left) // 2
                    coins = middle * (middle + 1) // 2
        
                    if coins == n:
                        return middle
                    
                    if coins > n:
                        right = middle - 1
                    else:
                        left = middle + 1
                
                return right
        

        4.7.1453 - 2023-07-23 20:03:43 +0300 MSK

        Arranging Coins

        Code

        class Solution:
            def arrangeCoins(self, n: int) -> int:
                count = 0
                row = 1
                while n >= row:
                    n -= row
                    row += 1
                    count += 1
        
                return count
        

        4.7.1454 - 2023-07-23 19:57:13 +0300 MSK

        Middle of the Linked List

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
                slow = fast = head
                while fast and fast.next:
                    slow = slow.next
                    fast = fast.next.next
                
                return slow
        

        4.7.1455 - 2023-07-23 19:55:42 +0300 MSK

        Middle of the Linked List

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
                middle = head.next if head else None 
                tail = middle.next if middle else None
                move = True
                while tail and tail.next:
                    tail = tail.next
                    if move:
                        middle = middle.next
                    
                    move = not move
        
                return middle if middle else head
        

        4.7.1456 - 2023-07-23 16:50:34 +0300 MSK

        All Possible Full Binary Trees

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def allPossibleFBT(self, n: int) -> List[TreeNode]:
                if n % 2 == 0:
                    return []
                if n == 1:
                    return [TreeNode()]
        
                res = []
                for i in range(1, n, 2):
                    left = self.allPossibleFBT(i)
                    right = self.allPossibleFBT(n - i - 1)
        
                    for l in left:
                        for r in right:
                            root = TreeNode(0, l, r)
                            res.append(root)
        
                return res
        

        4.7.1457 - 2023-07-22 19:09:00 +0300 MSK

        Knight Probability in Chessboard

        Code

        class Solution:
            # y x x
            # x x x
            # x x x: (2 / 8) * (4 / 16) = 0.0625
            #        (1/8, 1/8), (2/8, 2/8)
            # 
            # x x x
            # x y x
            # x x x: 0
            def __init__(self):
                self.available_moves = (
                    (2, 1), (1, 2), (-2, 1), (-1, 2), (2, -1), (1, -2), 
                    (-2, -1), (-1, -2)
                )
            
        
            def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
                if k < 1:
                    return 1
                
                if n < 3:
                    return 0
        
                return self.calculate(row, column, n, k)
            
            @cache
            def calculate(self, row: int, column: int, size: int, 
                               moves_left: int) -> float:
               
                if moves_left < 1:
                    return 1
        
                probability = 0
        
                for row_add, column_add in self.available_moves:
                    new_row = row_add + row
                    new_column = column_add + column
        
                    if new_row < 0 or new_row >= size or (
                        new_column < 0 or new_column >= size
                    ):
                        continue
        
                    probability += self.calculate(
                        new_row, new_column, size, moves_left - 1
                    ) / 8
        
                return probability
        

        4.7.1458 - 2023-07-22 17:36:35 +0300 MSK

        Knight Probability in Chessboard

        Code

        class Solution:
            def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
                # Define possible directions for the knight's moves
                directions = [(1, 2), (1, -2), (-1, 2), (-1, -2),
                              (2, 1), (2, -1), (-2, 1), (-2, -1)]
        
                # Initialize the dynamic programming table
                dp = [[[0] * n for _ in range(n)] for _ in range(k + 1)]
                dp[0][row][column] = 1
        
                # Iterate over the number of moves
                for moves in range(1, k + 1):
                    # Iterate over the cells on the chessboard
                    for i in range(n):
                        for j in range(n):
                            # Iterate over possible directions
                            for direction in directions:
                                prev_i, prev_j = i - direction[0], j - direction[1]
                                # Check if the previous cell is within the chessboard
                                if 0 <= prev_i < n and 0 <= prev_j < n:
                                    # Add the previous probability
                                    dp[moves][i][j] += dp[moves - 1][prev_i][prev_j]
                            # Divide by 8
                            dp[moves][i][j] /= 8
        
                # Calculate total probability by summing probabilities for all cells
                total_probability = sum(
                    dp[k][i][j]
                    for i in range(n)
                    for j in range(n)
                )
                return total_probability
        

        4.7.1459 - 2023-07-21 16:55:34 +0300 MSK

        Repeated Substring Pattern

        Code

        class Solution:
            def repeatedSubstringPattern(self, s: str) -> bool:
                length = len(s)
                for i in range(1, length // 2 + 1):
                    if length % i != 0:
                        continue
                    
                    if s == s[:i] * (length // i):
                        return True
                
                return False
        

        4.7.1460 - 2023-07-21 16:53:22 +0300 MSK

        Repeated Substring Pattern

        Code

        class Solution:
            def repeatedSubstringPattern(self, s: str) -> bool:
                length = len(s)
                for i in range(length-1):
                    if length % (i + 1) != 0:
                        continue
                    
                    if s == s[:i+1] * (length // (i + 1)):
                        return True
                
                return False
        

        4.7.1461 - 2023-07-21 16:40:56 +0300 MSK

        Add Digits

        Code

        class Solution:
            def addDigits(self, num: int) -> int:
                sum = 0
                while num > 0:
                    sum += num % 10
                    num //= 10
                
                    if num == 0 and sum > 9:
                        num, sum = sum, 0
                        
                return sum
        

        4.7.1462 - 2023-07-21 16:40:33 +0300 MSK

        Add Digits

        Code

        class Solution:
            def addDigits(self, num: int) -> int:
                sum = 0
                while num > 0:
                    sum += num % 10
                    num //= 10
                
                    if num == 0 and sum > 9:
                        num, sum = sum, 0
                        
                return sum
        

        4.7.1463 - 2023-07-21 16:40:14 +0300 MSK

        Add Digits

        Code

        class Solution:
            def addDigits(self, num: int) -> int:
                sum = 0
                while num > 0:
                    sum += num % 10
                    num //= 10
                
                    if num == 0 and sum > 9:
                        num, sum = sum, 0
                        
                return sum
        

        4.7.1464 - 2023-07-21 16:36:57 +0300 MSK

        Add Digits

        Code

        class Solution:
            def addDigits(self, num: int) -> int:
                sum = num
                while sum > 9:
                    current_number, current_sum = sum, 0
                    while current_number:
                        current_sum += current_number % 10
                        current_number //= 10
                    sum = current_sum
                return sum
        

        4.7.1465 - 2023-07-21 16:30:39 +0300 MSK

        Implement Queue using Stacks

        Code

        class MyQueue:
        
            def __init__(self):
                self.stack_in = []
                self.stack_out = []
        
            def push(self, x: int) -> None:
                self.stack_in.append(x)
        
            def pop(self) -> int:
                self.peek()
                return self.stack_out.pop()
        
            def peek(self) -> int:
                if self.stack_out:
                    return self.stack_out[-1]
                
                while self.stack_in:
                    self.stack_out.append(self.stack_in.pop())
        
                return self.stack_out[-1]
        
            def empty(self) -> bool:
                return not self.stack_out and not self.stack_in
        
        
        # Your MyQueue object will be instantiated and called as such:
        # obj = MyQueue()
        # obj.push(x)
        # param_2 = obj.pop()
        # param_3 = obj.peek()
        # param_4 = obj.empty()
        

        4.7.1466 - 2023-07-21 16:20:49 +0300 MSK

        Implement Queue using Stacks

        Code

        class MyQueue:
        
            def __init__(self):
                self.queue = []
        
            def push(self, x: int) -> None:
                self.queue.insert(0, x)
        
            def pop(self) -> int:
                return self.queue.pop()
        
            def peek(self) -> int:
                return self.queue[-1]
        
            def empty(self) -> bool:
                return len(self.queue) == 0
        
        
        # Your MyQueue object will be instantiated and called as such:
        # obj = MyQueue()
        # obj.push(x)
        # param_2 = obj.pop()
        # param_3 = obj.peek()
        # param_4 = obj.empty()
        

        4.7.1467 - 2023-07-21 16:09:40 +0300 MSK

        Implement Queue using Stacks

        Code

        class MyQueue:
        
            def __init__(self):
                self.queue = deque()
        
            def push(self, x: int) -> None:
                self.queue.appendleft(x)
        
            def pop(self) -> int:
                return self.queue.pop()
        
            def peek(self) -> int:
                return self.queue[-1]
        
            def empty(self) -> bool:
                return len(self.queue) == 0
        
        
        # Your MyQueue object will be instantiated and called as such:
        # obj = MyQueue()
        # obj.push(x)
        # param_2 = obj.pop()
        # param_3 = obj.peek()
        # param_4 = obj.empty()
        

        4.7.1468 - 2023-07-21 16:06:08 +0300 MSK

        Power of Two

        Code

        class Solution:
            def isPowerOfTwo(self, n: int) -> bool:
                if n == 1:
                    return True
        
                while n > 2 and not n % 2:
                    n //= 2
                return n == 2
        

        4.7.1469 - 2023-07-21 15:59:33 +0300 MSK

        Remove Duplicates from Sorted List

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
                result = head
                
                while head and head.next:
                    if head.next.val == head.val:
                        head.next = head.next.next
                        continue
                    
                    head = head.next
                
                return result
        

        4.7.1470 - 2023-07-21 15:52:55 +0300 MSK

        Climbing Stairs

        Code

        class Solution:
            # 1: 1
            # 2: 2
            # 3: 3 [2(2), 1(1)]
            # 4: 5 [3(3), (2)]
            def climbStairs(self, n: int) -> int:
                if n < 3:
                    return n
        
                count, count_prev = 2, 1
                for number in range(3, n + 1):
                    count, count_prev = count + count_prev, count
                return count
        

        4.7.1471 - 2023-07-21 15:33:25 +0300 MSK

        Plus One

        Code

        class Solution:
            def plusOne(self, digits: List[int]) -> List[int]:
                carry = 1
                for i in reversed(range(len(digits))):
                    new_digit = digits[i] + carry
                    if new_digit > 9:
                        carry = 1
                        new_digit %= 10
                    else:
                        carry = 0
                    digits[i] = new_digit
                
                if carry:
                    digits.insert(0, carry)
                
                return digits
        

        4.7.1472 - 2023-07-21 13:34:45 +0300 MSK

        Number of Steps to Reduce a Number to Zero

        Code

        class Solution:
            def numberOfSteps(self, num: int) -> int:
                count = 0
                while num:
                    count += 1
                    if num % 2 == 0:
                        num /= 2
                    else:
                        num -= 1
                
                return count
                    
        

        4.7.1473 - 2023-07-21 13:33:01 +0300 MSK

        Fizz Buzz

        Code

        class Solution:
            def fizzBuzz(self, n: int) -> List[str]:
                result = []
        
                for i in range(1, n + 1):
                    div_by_3, div_by_5 = i % 3 == 0, i % 5 == 0
                    value = None
        
                    if div_by_3 and div_by_5:
                        value = "FizzBuzz"
                    elif div_by_3:
                        value = "Fizz"
                    elif div_by_5:
                        value = "Buzz"
                    else:
                        value = str(i)
                    
                    result.append(value)
                
                return result
        

        4.7.1474 - 2023-07-21 13:26:34 +0300 MSK

        Richest Customer Wealth

        Code

        class Solution:
            def maximumWealth(self, accounts: List[List[int]]) -> int:
                max_wealth = 0
                for i in range(len(accounts)):
                    wealth = 0
                    for j in range(len(accounts[i])):
                        wealth += accounts[i][j]
                    
                    if wealth > max_wealth:
                        max_wealth = wealth
                
                return max_wealth
        

        4.7.1475 - 2023-07-21 13:23:06 +0300 MSK

        Running Sum of 1d Array

        Code

        class Solution:
            def runningSum(self, nums: List[int]) -> List[int]:
                for i in range(1, len(nums)):
                    nums[i] += nums[i-1]
                return nums
        

        4.7.1476 - 2023-07-21 13:19:55 +0300 MSK

        Root Equals Sum of Children

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def checkTree(self, root: Optional[TreeNode]) -> bool:
                return root.val == (root.left.val + root.right.val)
        

        4.7.1477 - 2023-07-21 13:18:37 +0300 MSK

        Add Two Integers

        Code

        class Solution:
            def sum(self, num1: int, num2: int) -> int:
                return num1 + num2
        

        4.7.1478 - 2023-07-21 13:11:37 +0300 MSK

        Number of Longest Increasing Subsequence

        Code

        class Solution:
            def findNumberOfLIS(self, nums: List[int]) -> int:
                n = len(nums)
                if n <= 1:
                    return n
        
                lengths = [1] * n
                counts = [1] * n
        
                for i in range(1, n):
                    for j in range(i):
                        if nums[i] > nums[j]:
                            if lengths[j] + 1 > lengths[i]:
                                lengths[i] = lengths[j] + 1
                                counts[i] = counts[j]
                            elif lengths[j] + 1 == lengths[i]:
                                counts[i] += counts[j]
        
                max_length = max(lengths)
                return sum(count for length, count in zip(lengths, counts) if length == max_length)
        

        4.7.1479 - 2023-07-20 12:12:22 +0300 MSK

        Asteroid Collision

        Code

        class Solution:
            def asteroidCollision(self, asteroids: List[int]) -> List[int]:
                stack = []
                for asteroid in asteroids:
                    if asteroid > 0:
                        stack.append(asteroid)
                        continue
                    
                    asteroid_abs = abs(asteroid)
                    while stack and stack[-1] > 0 and stack[-1] < asteroid_abs:
                        stack.pop()
                    
                    if stack and stack[-1] == asteroid_abs:
                        stack.pop()
                    elif not stack or stack[-1] < 0:
                        stack.append(asteroid)
        
                return stack
        

        4.7.1480 - 2023-07-20 11:41:51 +0300 MSK

        Asteroid Collision

        Code

        class Solution:
            def asteroidCollision(self, asteroids: List[int]) -> List[int]:
                length = len(asteroids)
        
                if length < 2:
                    return asteroids
        
                stack = [asteroids[0]]
                for i in range(1, length):
                    asteroid = asteroids[i]
                    asteroid_last = stack[-1] if stack else 0
                    stack.append(asteroid)
        
                    if asteroid > 0 or (
                        asteroid < 0 and asteroid_last < 0
                    ):
                        continue
        
                    while len(stack) >= 2 and stack[-1] < 0 and stack[-2] > 0:
                        last, prev = abs(stack[-1]), abs(stack[-2])
                        if last == prev:
                            stack.pop()
                        elif last > prev:
                            stack[-1], stack[-2] = stack[-2], stack[-1]
        
                        stack.pop()
        
                return stack
        

        4.7.1481 - 2023-07-19 14:35:52 +0300 MSK

        Best Time to Buy and Sell Stock II

        Code

        class Solution:
            def maxProfit(self, prices: List[int]) -> int:
        		# It is impossible to sell stock on first day, set -infinity as initial value for cur_hold
                cur_hold, cur_not_hold = -float('inf'), 0
                
                for stock_price in prices:
                    prev_hold, prev_not_hold = cur_hold, cur_not_hold
        			# either keep hold, or buy in stock today at stock price
                    cur_hold = max(prev_hold, prev_not_hold - stock_price)
        			
        			# either keep not-hold, or sell out stock today at stock price
                    cur_not_hold = max(prev_not_hold, 
                                       prev_hold + stock_price)
                    
                # maximum profit must be in not-hold state
                return cur_not_hold
        

        4.7.1482 - 2023-07-19 14:26:39 +0300 MSK

        Gas Station

        Code

        class Solution:
            def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
                if sum(gas) < sum(cost): 
                    return -1
                
                tank, idx = 0, 0
                for i in range(len(gas)):
                    tank += gas[i] - cost[i] 
                    if tank < 0: 
                        tank, idx = 0, i+1
                return idx 
        

        4.7.1483 - 2023-07-19 14:19:51 +0300 MSK

        Jump Game II

        Code

        class Solution:
            def jump(self, nums: List[int]) -> int:
                length = len(nums)
                result = 0
                end = 0
                farthest = 0
        
                for i in range(length - 1):
                    number = nums[i]
                    max_jump = i + number
                    if max_jump > farthest:
                        farthest = max_jump
        
                    if farthest >= length - 1:
                        result += 1
                        break
                    
                    if i == end:
                        result += 1
                        end = farthest
        
        
                return result
        

        4.7.1484 - 2023-07-19 14:19:26 +0300 MSK

        Minimum Size Subarray Sum

        Code

        class Solution:
            def minSubArrayLen(self, target: int, nums: List[int]) -> int:
                left = 0
                sum_of_subarray = 0
                min_length = float('inf')
                
                for right in range(len(nums)):
                    sum_of_subarray += nums[right]
                    
                    while sum_of_subarray >= target:
                        min_length = min(min_length, right - left + 1)
                        sum_of_subarray -= nums[left]
                        left += 1
        
                if min_length == float('inf'):
                    return 0
        
                return min_length
        

        4.7.1485 - 2023-07-19 13:39:31 +0300 MSK

        H-Index

        Code

        class Solution:
            # [3,0,6,1,5]
            # [0,1,3,5,6]
            def hIndex(self, citations: List[int]) -> int:
                citations = sorted(citations)
                length = len(citations)
        
                h = 0
                for i in reversed(range(length)):
                    citations_count = citations[i]
                    published_count = length - i
        
                    if citations_count == 0 or published_count < h:
                        break
        
                    if published_count <= citations_count:
                        h = published_count
                    
                return h
        

        4.7.1486 - 2023-07-19 12:33:23 +0300 MSK

        Zigzag Conversion

        Code

        class Solution:
            def convert(self, s: str, numRows: int) -> str:
                if numRows < 2:
                    return s
                
                result: List[List[str]] = [[] for _ in range(numRows)]
            
                row, is_ascending, last = 0, True, numRows - 1
                for symbol in s:
                    result[row].append(symbol)
                    
                    if is_ascending and row < last:
                        row += 1
                    elif is_ascending:
                        is_ascending = False
                    
                    if is_ascending:
                        continue
        
                    if row > 0:
                        row -= 1
                    else:
                        is_ascending = True
                        row = 1
            
                
                return "".join("".join(row) for row in result)
        

        4.7.1487 - 2023-07-19 11:49:03 +0300 MSK

        Insert Delete GetRandom O(1)

        Code

        class RandomizedSet:
        
            def __init__(self):
                self._set = set()
                self._items = []
                self._indexes = {}
                
        
            def insert(self, val: int) -> bool:
                is_in = val in self._set
                if not is_in:
                    self._set.add(val)
                    self._items.append(val)
                    self._indexes[val] = len(self._items) - 1
                return not is_in
        
            def remove(self, val: int) -> bool:
                if val not in self._set:
                    return False
        
                last = self._items[-1]
                val_index = self._indexes[val]
                self._items[val_index] = last
                self._indexes[last] = val_index
                
                self._set.remove(val)
                self._items.pop()
                self._indexes.pop(val)
        
                return True
        
            def getRandom(self) -> int:
                return random.choice(self._items)
        
        
        # Your RandomizedSet object will be instantiated and called as such:
        # obj = RandomizedSet()
        # param_1 = obj.insert(val)
        # param_2 = obj.remove(val)
        # param_3 = obj.getRandom()
        

        4.7.1488 - 2023-07-19 11:34:17 +0300 MSK

        Jump Game

        Code

        class Solution:
            def canJump(self, nums: List[int]) -> bool:
                length = len(nums)
        
                if length < 2:
                    return True
                
                current = nums[0]
        
                for i in range(1, length):
                    if current == 0:
                        return False
                    current -= 1
                    current = max(current, nums[i])
                
                return True
                    
        

        4.7.1489 - 2023-07-19 11:26:05 +0300 MSK

        Letter Combinations of a Phone Number

        Code

        class Solution:
            def letterCombinations(self, digits: str) -> List[str]:
                length = len(digits)
                if length == 0:
                    return []
                
                digit_map: Dict[int, str] = {
                    1: [],
                    2: ["a", "b", "c"],
                    3: ["d", "e", "f"],
                    4: ["g", "h", "i"],
                    5: ["j", "k", "l"],
                    6: ["m", "n", "o"],
                    7: ["p", "q", "r", "s"],
                    8: ["t", "u", "v"],
                    9: ["w", "x", "y", "z"],
                    0: [" "]
                }
                result: List[List[str]] = [
                    digit_map[int(digit)] for digit in digits
                ]
                return ["".join(i) for i in product(*result)]
        

        4.7.1490 - 2023-07-19 11:25:19 +0300 MSK

        Letter Combinations of a Phone Number

        Code

        class Solution:
            def letterCombinations(self, digits: str) -> List[str]:
                length = len(digits)
                if length == 0:
                    return []
                
                digit_map: Dict[int, str] = {
                    1: [],
                    2: ["a", "b", "c"],
                    3: ["d", "e", "f"],
                    4: ["g", "h", "i"],
                    5: ["j", "k", "l"],
                    6: ["m", "n", "o"],
                    7: ["p", "q", "r", "s"],
                    8: ["t", "u", "v"],
                    9: ["w", "x", "y", "z"],
                    0: [" "]
                }
                result: List[List[str]] = [
                    digit_map[int(digit)] for digit in digits
                ]
                return ["".join(i) for i in product(*result)]
        

        4.7.1491 - 2023-07-19 11:14:44 +0300 MSK

        Non-overlapping Intervals

        Code

        class Solution:
            def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
                intervals = sorted(intervals, key=lambda element: element[1])
                length = len(intervals)
                prev, count = 0, 1
        
                for i in range(1, length):
                    if intervals[i][0] < intervals[prev][1]:
                        continue
                    
                    prev = i
                    count += 1
                
                return length - count
        

        4.7.1492 - 2023-07-18 18:51:03 +0300 MSK

        Add Two Numbers

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            # create the result pointer that points towards one of the lists
            # create the result root pointer that will point towards the root of the result list
            # 1. start infinite loop
            # 2. if result is false - break, we reached the end
            # 3. get values from non-empty pointers
            # 4. add values together, store the carry in a variable
            # 5. store the value in the result pointer
            # 6. move the result pointer to the next node, if there is no next node, use a node from
            #    another list
            # 7. move list pointers
            # 8. if we have a carry left, add a node to the result list
            def addTwoNumbers(self, l1: Optional[ListNode], 
                                    l2: Optional[ListNode]) -> Optional[ListNode]:
                carry = 0
                result, result_root = l1, l1
        
                while True:
                    if not l1 and not l2:
                        break
                    
                    number_1 = l1.val if l1 else 0
                    number_2 = l2.val if l2 else 0
                    result_val = number_1 + number_2 + carry
                    if result_val > 9:
                        carry, result_val = 1, result_val - 10
                    else:
                        carry = 0
                    
                    result.val = result_val
                    if not result.next and l2:
                        l1 = None
                        result.next = l2.next
        
                    if result.next:
                        result = result.next
                    if l1:
                        l1 = l1.next
                    if l2:
                        l2 = l2.next
        
                if carry:
                    result.next = ListNode(carry)
        
                return result_root
        

        4.7.1493 - 2023-07-18 18:50:17 +0300 MSK

        LRU Cache

        Code

        class LRUCache:
            class Node:
                def __init__(self, key: str, val: int) -> None:
                    self.key = key
                    self.val = val
                    self.prev: Node = None
                    self.next: Node = None
        
            def __init__(self, capacity: int) -> None:
                self.cap = capacity
                self.head = self.Node(-1, -1)
                self.tail = self.Node(-1, -1)
                self.head.next = self.tail
                self.tail.prev = self.head
                self.cache = {}
        
            def add_node(self, new_node: Node) -> None:
                old_first_node = self.head.next
                new_node.next = old_first_node
                new_node.prev = self.head
                self.head.next = new_node
                old_first_node.prev = new_node
        
            def delete_node(self, delete_node: Node) -> None:
                prev = delete_node.prev
                next = delete_node.next
                prev.next = next
                next.prev = prev
        
            def get(self, key: int) -> int:
                if key not in self.cache:
                    return -1
                result_node = self.cache[key]
                result = result_node.val
                del self.cache[key]
                self.delete_node(result_node)
                self.add_node(result_node)
                self.cache[key] = self.head.next
                return result
            
        
            def put(self, key: int, value: int) -> None:
                if key in self.cache:
                    current = self.cache[key]
                    del self.cache[key]
                    self.delete_node(current)
        
                if len(self.cache) == self.cap:
                    del self.cache[self.tail.prev.key]
                    self.delete_node(self.tail.prev)
        
                self.add_node(self.Node(key, value))
                self.cache[key] = self.head.next
        
        # Your LRUCache object will be instantiated and called as such:
        # obj = LRUCache(capacity)
        # param_1 = obj.get(key)
        # obj.put(key,value)
        

        4.7.1494 - 2023-07-18 18:39:57 +0300 MSK

        LRU Cache

        Code

        class LRUCache:
            class Node:
                def __init__(self, key: str, val: int) -> None:
                    self.key = key
                    self.val = val
                    self.prev: Node = None
                    self.next: Node = None
        
            def __init__(self, capacity: int) -> None:
                self.cap = capacity
                self.head = self.Node(-1, -1)
                self.tail = self.Node(-1, -1)
                self.head.next = self.tail
                self.tail.prev = self.head
                self.cache = {}
        
            def add_node(self, new_node: Node) -> None:
                old_first_node = self.head.next
                new_node.next = old_first_node
                new_node.prev = self.head
                self.head.next = new_node
                old_first_node.prev = new_node
        
            def delete_node(self, delete_node: Node) -> None:
                prev = delete_node.prev
                next = delete_node.next
                prev.next = next
                next.prev = prev
        
            def get(self, key: int) -> int:
                if key not in self.cache:
                    return -1
                result_node = self.cache[key]
                result = result_node.val
                del self.cache[key]
                self.delete_node(result_node)
                self.add_node(result_node)
                self.cache[key] = self.head.next
                return result
            
        
            def put(self, key: int, value: int) -> None:
                if key in self.cache:
                    current = self.cache[key]
                    del self.cache[key]
                    self.delete_node(current)
        
                if len(self.cache) == self.cap:
                    del self.cache[self.tail.prev.key]
                    self.delete_node(self.tail.prev)
        
                self.add_node(self.Node(key, value))
                self.cache[key] = self.head.next
        
        # Your LRUCache object will be instantiated and called as such:
        # obj = LRUCache(capacity)
        # param_1 = obj.get(key)
        # obj.put(key,value)
        

        4.7.1495 - 2023-07-18 18:25:23 +0300 MSK

        Search a 2D Matrix

        Code

        class Solution:
            def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
                length_vertical, length_horizontal = len(matrix), len(matrix[0])
        
        
                left, right = 0, length_vertical - 1
                while left <= right:
                    mid = left + (right - left) // 2
                    mid_number = matrix[mid][0]
                    
                    if mid_number == target:
                        return True
                    
                    if mid_number > target:
                        right = mid - 1
                    else:
                        left = mid + 1
                
                vertical_index = right
                left, right = 0, length_horizontal - 1
                while left <= right:
                    mid = left + (right - left) // 2
                    mid_number = matrix[vertical_index][mid]
        
                    if mid_number == target:
                        return True
                    
                    if mid_number > target:
                        right = mid - 1
                    else:
                        left = mid + 1
                    
                return False
        

        4.7.1496 - 2023-07-18 18:14:47 +0300 MSK

        Search Insert Position

        Code

        class Solution:
            def searchInsert(self, nums: List[int], target: int) -> int:
                length = len(nums)
                left, right = 0, length - 1
        
                while left <= right:
                    mid = left + (right - left) // 2
                    mid_number = nums[mid]
        
                    if mid_number == target:
                        return mid
        
                    if mid_number > target:
                        right = mid - 1
                    else:
                        left = mid + 1
        
                return left
        

        4.7.1497 - 2023-07-18 18:10:20 +0300 MSK

        Sqrt(x)

        Code

        class Solution:
            def mySqrt(self, x: int) -> int:
                if x == 0 or x == 1:
                    return x
        
                left, right = 1, x
        
                while left <= right:
                    mid = left + (right - left) // 2
                    square = mid * mid
        
                    if square == x:
                        return mid
                    
                    if square > x:
                        right = mid - 1 
                    else:
                        left = mid + 1
                    
                return right
        

        4.7.1498 - 2023-07-18 18:02:32 +0300 MSK

        Palindrome Number

        Code

        class Solution:
            def isPalindrome(self, x: int) -> bool:
                if x < 0:
                    return False
                
                if x < 10:
                    return True
                
                number = []
        
                while x:
                    remainder = x % 10
                    x = x // 10
                    number.append(remainder)
                    
                length = len(number)
                half_index = length // 2
        
                for i, digit in enumerate(number):
                    last_digit = number[length - i - 1]
        
                    if digit != last_digit:
                        return False
                    
                    if i != half_index:
                        continue
                    
                    return True
        

        4.7.1499 - 2023-07-18 18:01:12 +0300 MSK

        Palindrome Number

        Code

        class Solution:
            def isPalindrome(self, x: int) -> bool:
                if x < 0:
                    return False
                
                if x < 10:
                    return True
                
                number = []
        
                while x:
                    remainder = x % 10
                    x = x // 10
                    number.append(remainder)
                    
                length = len(number)
                half_index = length // 2
        
                for i, digit in enumerate(number):
                    last_digit = number[length - i - 1]
        
                    if digit != last_digit:
                        return False
                    
                    if i != half_index:
                        continue
                    
                    return True
        

        4.7.1500 - 2023-07-18 17:58:35 +0300 MSK

        Evaluate Reverse Polish Notation

        Code

        class Solution:
            def evalRPN(self, tokens: List[str]) -> int:
                stack = []
                operations = {
                    "+": lambda first, second: first + second,
                    "-": lambda first, second: first - second,
                    "*": lambda first, second: first * second,
                    "/": lambda first, second: int(first / second)
                }
                for token in tokens:
                    if token not in operations:
                        stack.append(int(token))
                        continue
        
                    second, first = stack.pop(), stack.pop()
                    result = operations[token](first, second)
                    stack.append(result)
                    
                return stack[-1]
        

        4.7.1501 - 2023-07-18 17:57:21 +0300 MSK

        Add Two Numbers II

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def reverse(self, head: ListNode) -> ListNode:
                previous = None
                while head:
                    next, head.next = head.next, previous
                    previous, head = head, next
                return previous
        
            def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
                l1, l2 = self.reverse(l1), self.reverse(l2)
                head, tail, carry = l1, l1, 0
        
                while l1 or l2 or carry:
                    val_1 = l1.val if l1 else 0
                    val_2 = l2.val if l2 else 0
                    sum = val_1 + val_2 + carry
                    if sum > 9:
                        carry = 1
                        sum %= 10
                    else:
                        carry = 0
        
                    tail.val = sum
                    l1, l2 = l1.next if l1 else None, l2.next if l2 else None
                    if not tail.next and l2:
                        tail.next = l2
                        l1 = None
        
                    if not tail.next and carry:
                        tail.next = ListNode(carry)
                        carry = 0
                        l2 = None
        
                    if tail.next:
                        tail = tail.next
                    
                return self.reverse(head)
        

        4.7.1502 - 2023-07-18 17:10:30 +0300 MSK

        Reverse Linked List

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
                previous = None
                while head:
                    next, head.next = head.next, previous
                    previous, head = head, next
        
                return previous
        

        4.7.1503 - 2023-07-18 16:55:29 +0300 MSK

        Two Sum II - Input Array Is Sorted

        Code

        class Solution:
            def twoSum(self, numbers: List[int], target: int) -> List[int]:
                numbers_map: Dict[str, int] = {}
        
                for i, number in enumerate(numbers):
                    diff = target - number
                    if diff in numbers_map:
                        return [numbers_map[diff] + 1, i + 1]
                    numbers_map[number] = i
                
                return []
        

        4.7.1504 - 2023-07-18 16:41:40 +0300 MSK

        Reverse Words in a String

        Code

        class Solution:
            def reverseWords(self, s: str) -> str:
                return " ".join(s.split()[::-1])
        

        4.7.1505 - 2023-07-18 16:37:43 +0300 MSK

        Integer to Roman

        Code

        class Solution:
            def intToRoman(self, num: int) -> str:
                result: List[str] = []
                stack: List[int] = deque([
                    1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000
                ])
                values = {
                    1000: "M",
                    900: "CM",
                    500: "D",
                    400: "CD",
                    100: "C",
                    90: "XC",
                    50: "L",
                    40: "XL",
                    10: "X",
                    9: "IX",
                    5: "V",
                    4: "IV",  
                    1: "I"
                }
        
                while num:
                    roman = stack[-1]
                    if num < roman:
                        stack.pop()
                        continue
        
                    result.append(values[roman])
                    num -= roman
        
                return "".join(result)
        

        4.7.1506 - 2023-07-18 16:15:43 +0300 MSK

        Evaluate Reverse Polish Notation

        Code

        class Solution:
            def evalRPN(self, tokens: List[str]) -> int:
                stack = []
                operations = {
                    "+": lambda first, second: first + second,
                    "-": lambda first, second: first - second,
                    "*": lambda first, second: first * second,
                    "/": lambda first, second: int(first / second)
                }
                for token in tokens:
                    if token not in operations:
                        stack.append(int(token))
                        continue
        
                    second, first = stack.pop(), stack.pop()
                    result = operations[token](first, second)
                    stack.append(result)
                    
                return stack[-1]
        

        4.7.1507 - 2023-07-18 15:49:17 +0300 MSK

        Min Stack

        Code

        from sortedcontainers import sortedset
        
        class MinStack:
        
            def __init__(self):
                self.stack: List[int] = []
                self.min_stack: List[int] = []
        
            def push(self, val: int) -> None:
                self.stack.append(val)
                if not self.min_stack or val <= self.min_stack[-1]:
                    self.min_stack.append(val)
        
            def pop(self) -> None:
                if not self.stack:
                    return
                pop = self.stack.pop()
                if pop == self.min_stack[-1]:
                    self.min_stack.pop()
        
            def top(self) -> int:
                return self.stack[-1]
        
            def getMin(self) -> int:
                return self.min_stack[-1]
        
        
        # Your MinStack object will be instantiated and called as such:
        # obj = MinStack()
        # obj.push(val)
        # obj.pop()
        # param_3 = obj.top()
        # param_4 = obj.getMin()
        

        4.7.1508 - 2023-07-18 15:46:05 +0300 MSK

        Min Stack

        Code

        from sortedcontainers import sortedset
        
        class MinStack:
            class Node:
                def __init__(self, val: int, prev: 'Node'):
                    self.val = val
                    self.prev = prev
        
        
            def __init__(self):
                self.stack: List[Node] = []
                self.min_node = None
        
            def push(self, val: int) -> None:
                new_node = self.Node(val, None)
                self.stack.append(new_node)
                if self.min_node is None or val <= self.min_node.val:
                    new_node.prev = self.min_node
                    self.min_node = new_node
        
            def pop(self) -> None:
                pop = self.stack.pop()
                if pop == self.min_node:
                    self.min_node = self.min_node.prev
        
            def top(self) -> int:
                return self.stack[-1].val
        
            def getMin(self) -> int:
                return self.min_node.val
        
        
        # Your MinStack object will be instantiated and called as such:
        # obj = MinStack()
        # obj.push(val)
        # obj.pop()
        # param_3 = obj.top()
        # param_4 = obj.getMin()
        

        4.7.1509 - 2023-07-18 15:23:22 +0300 MSK

        Simplify Path

        Code

        class Solution:
            def simplifyPath(self, path: str) -> str:
                canonical = []
                for directory in path.split("/"):
                    if not directory or directory == ".":
                        continue
                    
                    if directory != "..":
                        canonical.append(directory)
                        continue
                    
                    if len(canonical):
                        canonical.pop()
        
                return "/" + "/".join(canonical)
        

        4.7.1510 - 2023-07-18 15:15:34 +0300 MSK

        Longest Consecutive Sequence

        Code

        class Solution:
            def longestConsecutive(self, nums: List[int]) -> int:
                length = len(nums)
                if length < 2:
                    return length
                
                nums = set(nums)
                longest = 1
                for number in nums:
                    if number - 1 in nums:
                        continue
                    consequent = 1
                    while number + consequent in nums:
                        consequent += 1
                    longest = max(longest, consequent)
                
                return longest
        

        4.7.1511 - 2023-07-18 15:08:44 +0300 MSK

        Longest Consecutive Sequence

        Code

        from sortedcontainers import SortedSet
        
        class Solution:
            def longestConsecutive(self, nums: List[int]) -> int:
                nums = SortedSet(nums)
                longest, current = 0, 0
                for number in nums:
                    if number - 1 in nums:
                        current += 1
                        continue
                    if current > longest:
                        longest = current
                    current = 1
                return max(current, longest)
                    
        

        4.7.1512 - 2023-07-18 14:53:17 +0300 MSK

        Group Anagrams

        Code

        class Solution:
            def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
                anagrams: Dict[str, List[str]] = defaultdict(list)
        
                for string in strs:
                    anagrams["".join(sorted(string))].append(string)
                
                return anagrams.values()
        

        4.7.1513 - 2023-07-18 14:46:38 +0300 MSK

        LRU Cache

        Code

        class LRUCache:
            class Node:
                def __init__(self, key: str, val: int) -> None:
                    self.key = key
                    self.val = val
                    self.prev: Node = None
                    self.next: Node = None
        
            def __init__(self, capacity: int) -> None:
                self.cap = capacity
                self.head = self.Node(-1, -1)
                self.tail = self.Node(-1, -1)
                self.head.next = self.tail
                self.tail.prev = self.head
                self.cache = {}
        
            def add_node(self, new_node: Node) -> None:
                old_first_node = self.head.next
                new_node.next = old_first_node
                new_node.prev = self.head
                self.head.next = new_node
                old_first_node.prev = new_node
        
            def delete_node(self, delete_node: Node) -> None:
                prev = delete_node.prev
                next = delete_node.next
                prev.next = next
                next.prev = prev
        
            def get(self, key: int) -> int:
                if key not in self.cache:
                    return -1
                result_node = self.cache[key]
                result = result_node.val
                del self.cache[key]
                self.delete_node(result_node)
                self.add_node(result_node)
                self.cache[key] = self.head.next
                return result
            
        
            def put(self, key: int, value: int) -> None:
                if key in self.cache:
                    current = self.cache[key]
                    del self.cache[key]
                    self.delete_node(current)
        
                if len(self.cache) == self.cap:
                    del self.cache[self.tail.prev.key]
                    self.delete_node(self.tail.prev)
        
                self.add_node(self.Node(key, value))
                self.cache[key] = self.head.next
        
        # Your LRUCache object will be instantiated and called as such:
        # obj = LRUCache(capacity)
        # param_1 = obj.get(key)
        # obj.put(key,value)
        

        4.7.1514 - 2023-07-18 13:48:20 +0300 MSK

        Rotate Array

        Code

        class Solution:
            def rotate(self, nums: List[int], k: int) -> None:
                """
                Do not return anything, modify nums in-place instead.
                """
                length = len(nums)
                k %= length
                nums[length - k:] = nums[length - k:][::-1]  
                nums[:length - k] = nums[:length - k][::-1]   
                nums[:] = nums[::-1] 
        

        4.7.1515 - 2023-07-16 19:26:31 +0300 MSK

        Remove Duplicates from Sorted Array II

        Code

        class Solution:
            def removeDuplicates(self, nums: List[int]) -> int:
                length = len(nums)
        
                if length < 2:
                    return length
                
                current_index = 2
        
                for number in nums[2:]:
                    if number == nums[current_index-2]:
                        continue
                    
                    nums[current_index] = number
                    current_index += 1
        
                return current_index
        

        4.7.1516 - 2023-07-16 19:19:33 +0300 MSK

        Remove Duplicates from Sorted Array II

        Code

        class Solution:
            def removeDuplicates(self, nums: List[int]) -> int:
                length = len(nums)
        
                if length < 2:
                    return length
                
                current_number, unique, current_index = nums[0], True, 1
                for number in nums[1:]:
                    if current_number != number:
                        current_number = number
                        unique = True
                        nums[current_index] = number
                        current_index += 1
                        continue
        
                    if unique:
                        nums[current_index] = number
                        current_index += 1
                        unique = False
        
                return current_index
        

        4.7.1517 - 2023-07-16 18:35:46 +0300 MSK

        Same Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
                if p and not q or (q and not p):
                    return False
                
                if not p and not q:
                    return True
                
                if p.val != q.val:
                    return False
                
                return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
        

        4.7.1518 - 2023-07-16 15:06:38 +0300 MSK

        Maximum Depth of Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def maxDepth(self, root: Optional[TreeNode], depth: int = 0) -> int:
                if not root:
                    return depth
        
                return max(self.maxDepth(root.left, depth + 1), self.maxDepth(root.right, depth + 1))
                
        

        4.7.1519 - 2023-07-16 15:04:36 +0300 MSK

        Maximum Depth of Binary Tree

        Code

        # Definition for a binary tree node.
        # class TreeNode:
        #     def __init__(self, val=0, left=None, right=None):
        #         self.val = val
        #         self.left = left
        #         self.right = right
        class Solution:
            def maxDepth(self, root: Optional[TreeNode], count: int = 0) -> int:
                if not root:
                    return 0
                
                if not root.left and not root.right:
                    return count + 1
        
                return max(self.maxDepth(root.left, count + 1), self.maxDepth(root.right, count + 1))
                
        

        4.7.1520 - 2023-07-16 13:34:50 +0300 MSK

        Merge Two Sorted Lists

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        
        class Solution:
            def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
                if not list1:
                    return list2
                
                if not list2:
                    return list1
                
                head = None
                if list1.val < list2.val:
                    head, list1 = list1, list1.next 
                else:
                    head, list2 = list2, list2.next
                
                current = head
                while list1 and list2:
                    if list1.val < list2.val:
                        current.next, list1 = list1, list1.next
                    else:
                        current.next, list2 = list2, list2.next
                    
                    current = current.next
        
                if list1 or list2:
                    current.next = list1 if list1 else list2
        
                return head
        

        4.7.1521 - 2023-07-16 12:53:42 +0300 MSK

        Linked List Cycle

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, x):
        #         self.val = x
        #         self.next = None
        
        class Solution:
            def hasCycle(self, head: Optional[ListNode]) -> bool:
                slow_p, fast_p = head, head.next if head else None
                while fast_p and fast_p.next:
                    if slow_p == fast_p:
                        return True
                    slow_p, fast_p = slow_p.next, fast_p.next.next
        
                return False
        

        4.7.1522 - 2023-07-16 12:51:01 +0300 MSK

        Linked List Cycle

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, x):
        #         self.val = x
        #         self.next = None
        
        class Solution:
            def hasCycle(self, head: Optional[ListNode]) -> bool:
                slow_p, fast_p = head, head.next if head else None
                while slow_p and fast_p:
                    if slow_p == fast_p:
                        return True
                    slow_p = slow_p.next
                    fast_p = fast_p.next if fast_p else None
                    fast_p = fast_p.next if fast_p else None
                
                return False
        

        4.7.1523 - 2023-07-16 12:38:36 +0300 MSK

        Valid Parentheses

        Code

        class Solution:
            def isValid(self, s: str) -> bool:
                length = len(s)
                if length < 2:
                    return False
        
                brackets_open = {
                    "{": "}",
                    "(": ")",
                    "[": "]"
                }
                brackets_close = brackets_open.values()
                stack = [s[0]]
        
                for bracket in s[1:]:
                    if bracket not in brackets_close:
                        stack.append(bracket)
                        continue
        
                    if len(stack) == 0 or brackets_open.get(stack[-1]) != bracket:
                        return False
                    
                    stack.pop()
        
                return not len(stack) 
        

        4.7.1524 - 2023-07-16 12:17:02 +0300 MSK

        Contains Duplicate II

        Code

        class Solution:
            def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
                indexes = {}
                for i, number in enumerate(nums):
                    if number in indexes and abs(i - indexes[number]) <= k:
                        return True
                    indexes[number] = i
                return False
        
                    
        

        4.7.1525 - 2023-07-16 12:16:10 +0300 MSK

        Contains Duplicate II

        Code

        class Solution:
            def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
                indexes = defaultdict(set)
                for i, number in enumerate(nums):
                    if number in indexes and any(abs(i - j) <= k for j in indexes[number]):
                        return True
                    indexes[number].add(i)
                return False
        
                    
        

        4.7.1526 - 2023-07-16 10:47:21 +0300 MSK

        Happy Number

        Code

        class Solution:
            def isHappy(self, n: int) -> bool:
                sums = set()
                while n != 1:
                    if n in sums:
                        return False
                    sums.add(n)
                    
                    sum = 0
                    while n > 0:
                        sum += (n % 10 )**2
                        n = n // 10
                    n = sum
        
                return True
        

        4.7.1527 - 2023-07-16 10:41:43 +0300 MSK

        Happy Number

        Code

        class Solution:
            def isHappy(self, n: int) -> bool:
                while True:
                    sum = 0
                    while n > 0:
                        sum += (n % 10 )**2
                        n = n // 10
                    n = sum
                    if sum < 10:
                        break
        
                return n in [1, 7]
        

        4.7.1528 - 2023-07-16 10:41:26 +0300 MSK

        Happy Number

        Code

        class Solution:
            def isHappy(self, n: int) -> bool:
                while True:
                    sum = 0
                    while n > 0:
                        sum += (n % 10 )**2
                        n = n // 10
                    n = sum
                    print(n)
                    if sum < 10:
                        break
        
                return n in [1, 7]
        

        4.7.1529 - 2023-07-15 21:24:48 +0300 MSK

        Two Sum

        Code

        class Solution:
            def twoSum(self, nums: List[int], target: int) -> List[int]:
                indexes = {}
                for i, number in enumerate(nums):
                    diff = target - number
                    if diff in indexes: 
                        return [indexes[diff], i]
                    indexes[number] = i
        

        4.7.1530 - 2023-07-15 21:22:16 +0300 MSK

        Valid Anagram

        Code

        class Solution:
            def isAnagram(self, s: str, t: str) -> bool:
                s_length, t_length = len(s), len(t)
        
                if s_length != t_length:
                    return False
                
                count = defaultdict(int)
                for i, s_symbol in enumerate(s):
                    t_symbol = t[i]
                    count[s_symbol] += 1
                    count[t_symbol] -= 1
        
                return not any((i != 0 for i in count.values())) 
        

        4.7.1531 - 2023-07-15 21:11:36 +0300 MSK

        Word Pattern

        Code

        class Solution:
            def wordPattern(self, pattern: str, s: str) -> bool:
                words = s.split()
                words_length, pattern_length = len(words), len(pattern)
        
                if words_length != pattern_length:
                    return False
                
                symbol_to_word = {}
                word_to_symbol = {}
        
                for i, symbol in enumerate(pattern):
                    word = words[i]
                    symbol_in, word_in = symbol in symbol_to_word, word in word_to_symbol
        
                    if symbol_in and word_in and symbol_to_word[symbol] == word:
                        continue
        
                    if not symbol_in and not word_in:
                        symbol_to_word[symbol] = word
                        word_to_symbol[word] = symbol
                        continue
        
                    return False
                
                return True
                    
        

        4.7.1532 - 2023-07-15 20:53:31 +0300 MSK

        Isomorphic Strings

        Code

        class Solution:
            def isIsomorphic(self, s: str, t: str) -> bool:
                s_length, t_length = len(s), len(t)
                if s_length != t_length:
                    return False
                
                s_to_t = {}
                t_to_s = {}
                for i, s_symbol in enumerate(s):
                    t_symbol = t[i]
        
                    if s_symbol not in s_to_t and t_symbol not in t_to_s:
                        s_to_t[s_symbol] = t_symbol
                        t_to_s[t_symbol] = s_symbol
                    elif s_symbol in s_to_t and s_to_t[s_symbol] == t_symbol:
                        continue
                    else:
                        return False
                        
                return True
        

        4.7.1533 - 2023-07-15 20:49:31 +0300 MSK

        Isomorphic Strings

        Code

        class Solution:
            def isIsomorphic(self, s: str, t: str) -> bool:
                return list(map(s.index, s)) == list(map(t.index, t))
        

        4.7.1534 - 2023-07-15 20:05:44 +0300 MSK

        Ransom Note

        Code

        class Solution:
            def canConstruct(self, ransomNote: str, magazine: str) -> bool:
                ransom_i, magazine_i = 0, 0
                ransom_length, magazine_length = len(ransomNote), len(magazine)
        
                if magazine_length < ransom_length:
                    return False
                
                if ransom_length == 1:
                    return ransomNote in magazine
        
                symbols = [0 for _ in range(26)]
        
                for symbol in magazine:
                    symbols[ord(symbol)-97] += 1
        
                for symbol in ransomNote:
                    symbols[ord(symbol)-97] -= 1
                
                
                return not any((count < 0 for count in symbols))
        

        4.7.1535 - 2023-07-15 19:55:32 +0300 MSK

        Ransom Note

        Code

        class Solution:
            # two indexes: ransom_i, magazine_i
            # sort both ransomNote and magazine (ascending order)
            # while indexes have not reached the end:
            # - if ransom symbol is equal to the magazine_symbol: increase both indexes
            # - if it is not equal, increase only magazine index
            # return wheter the ranson index is equal to the length of the ransom
            def canConstruct(self, ransomNote: str, magazine: str) -> bool:
                ransom_i, magazine_i = 0, 0
                ransom_length, magazine_length = len(ransomNote), len(magazine)
        
                if magazine_length < ransom_length:
                    return False
                
                if ransom_length == 1:
                    return ransomNote in magazine
        
                ransomNote = sorted(ransomNote)
                magazine = sorted(magazine)
        
                while ransom_i < ransom_length and magazine_i < magazine_length:
                    ransom_symbol, magazine_symbol = ransomNote[ransom_i], magazine[magazine_i]
                    
                    if magazine_symbol > ransom_symbol:
                        return False
        
                    if ransom_symbol == magazine_symbol:
                        ransom_i += 1
                    
                    magazine_i += 1
        
                return ransom_i == ransom_length
        

        4.7.1536 - 2023-07-15 19:35:16 +0300 MSK

        Ransom Note

        Code

        class Solution:
            # two indexes: ransom_i, magazine_i
            # sort both ransomNote and magazine (ascending order)
            # while indexes have not reached the end:
            # - if ransom symbol is equal to the magazine_symbol: increase both indexes
            # - if it is not equal, increase only magazine index
            # return wheter the ranson index is equal to the length of the ransom
            def canConstruct(self, ransomNote: str, magazine: str) -> bool:
                ransom_i, magazine_i = 0, 0
                ransom_length, magazine_length = len(ransomNote), len(magazine)
                ransomNote = sorted(ransomNote)
                magazine = sorted(magazine)
        
                if magazine_length < ransom_length:
                    return False
        
                while ransom_i < ransom_length and magazine_i < magazine_length:
                    ransom_symbol, magazine_symbol = ransomNote[ransom_i], magazine[magazine_i]
                    
                    if ransom_symbol == magazine_symbol:
                        ransom_i += 1
                        
                    magazine_i += 1
        
                return ransom_i == ransom_length
        

        4.7.1537 - 2023-07-13 21:11:33 +0300 MSK

        Is Subsequence

        Code

        class Solution:
            # create two pointers, original and sub, both are zero
            # while either of those pointers have not reached the end:
            # - if original symbol is equal to the sub, move both pointer to the right
            # - if not, move original pointer to the right
            # if sub pointer reached the end, return True, otherwise False
            def isSubsequence(self, s: str, t: str) -> bool:
                original, sub = 0, 0
                original_length, sub_length = len(t), len(s)
        
                while original < original_length and sub < sub_length:
                    if s[sub] == t[original]:
                        original += 1
                        sub += 1
                        continue
                    
                    original += 1
        
                return sub == sub_length
        

        4.7.1538 - 2023-07-13 20:57:51 +0300 MSK

        Longest Common Prefix

        Code

        class Solution:
            
            def longestCommonPrefix(self, strs: List[str]) -> str:
                if len(strs) == 1:
                    return strs[0]
        
                min_length = min([len(string) for string in strs])
                prefix = strs[0][0:min_length]
                for string in strs:
                    if not prefix:
                        return ""
                    
                    while not string.startswith(prefix):
                        prefix = prefix[0:-1]
                    
                return prefix
        

        4.7.1539 - 2023-07-13 20:49:03 +0300 MSK

        Longest Common Prefix

        Code

        class Solution:
            
            def longestCommonPrefix(self, strs: List[str]) -> str:
                if len(strs) == 1:
                    return strs[0]
        
                min_length = min([len(string) for string in strs])
                for i in range(min_length, -1, -1):
                    current = strs[0][0:i+1]
                    for string in strs[1:]:
                        if string[0:i+1] != current:
                            break
                    else:
                        return current
        
                return ""    
        

        4.7.1540 - 2023-07-13 20:34:54 +0300 MSK

        Roman to Integer

        Code

        class Solution:
            def romanToInt(self, input_numbers: str) -> int:
                result = 0
                previous = None
                values = {
                    "I": 1,
                    "V": 5,
                    "X": 10,
                    "L": 50,
                    "C": 100,
                    "D": 500,
                    "M": 1000,
                }
                subtractions = set(["IV", "IX", "XL", "XC", "CD", "CM"])
        
                for number in input_numbers:
                    if f"{previous}{number}" in subtractions:
                        result += values[number] - values[previous] * 2
                    else:
                        result += values[number]
                    previous = number
                
                return result
                    
        

        4.7.1541 - 2023-07-13 20:32:03 +0300 MSK

        Majority Element

        Code

        class Solution:
            def majorityElement(self, nums: List[int]) -> int:
                return sorted(nums)[len(nums)//2]
                        
        

        4.7.1542 - 2023-07-13 20:30:18 +0300 MSK

        Best Time to Buy and Sell Stock

        Code

        class Solution:
            # Input: prices = [7,1,5,3,6,4]
            # Output: 5
            # Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
            # Note that buying on day 2 and selling on day 1 is not allowed because you must buy 
            # before you sell.
            def maxProfit(self, prices: List[int]) -> int:
                length = len(prices)
                if length < 2:
                    return 0
        
                left, right, profit = 0, 1, 0
                while right < length:
                    current_profit = prices[right] - prices[left]
                    is_profitable = current_profit > 0
                    if is_profitable and current_profit > profit:
                        profit = current_profit
                    elif not is_profitable:
                        left = right
                    
                    right += 1
        
                return profit
        

        4.7.1543 - 2023-07-13 20:19:45 +0300 MSK

        Best Time to Buy and Sell Stock

        Code

        class Solution:
            # Input: prices = [7,1,5,3,6,4]
            # Output: 5
            # Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
            # Note that buying on day 2 and selling on day 1 is not allowed because you must buy 
            # before you sell.
            def maxProfit(self, prices: List[int]) -> int:
                length = len(prices)
                if length < 2:
                    return 0
        
                left, right, profit = 0, 1, 0
                while right < length:
                    current_profit = prices[right] - prices[left]
                    if current_profit > 0:
                        profit = max(current_profit, profit)
                    else:
                        left = right
                    right += 1
        
                return profit
        

        4.7.1544 - 2023-07-13 19:37:36 +0300 MSK

        Majority Element

        Code

        class Solution:
            def majorityElement(self, nums: List[int]) -> int:
                return sorted(nums)[len(nums)//2]
                        
        

        4.7.1545 - 2023-07-13 19:13:31 +0300 MSK

        Remove Duplicates from Sorted Array

        Code

        class Solution:
            # non-decreasing order, so to remove the duplicates we just need to remove all 
            #    consequent duplicates
            # create replace index, set it to 1 - the first element is always unique
            # check if length is more than 1 to avoid out-of-bounds - 
            #   if the length is one, just return 1
            # iterate over nums starting from the second element:
            # - if the current number is not equal to the previous, 
            #   set nums[replace] to it, move the replace index
            # - if the current number is equal to the previous one, continue 
            # return replace 
            def removeDuplicates(self, nums: List[int]) -> int:
                replace = 1
                for i, number in enumerate(nums[1:], 1): 
                    if number == nums[i-1]:
                        continue
                    nums[replace] = number
                    replace += 1
                
                return replace
        

        4.7.1546 - 2023-07-13 19:03:15 +0300 MSK

        Remove Duplicates from Sorted Array

        Code

        class Solution:
            # non-decreasing order, so to remove the duplicates we just need to remove all 
            #    consequent duplicates
            # create replace index, set it to 0
            # create a set of duplicates
            # iterate over nums:
            # - if the number is in the set, continue
            # - if the number is not in the set, set nums[replace] to that number, add it to the set
            # return replace
            def removeDuplicates(self, nums: List[int]) -> int:
                replace, duplicates = 0, set()
                for i, number in enumerate(nums): 
                    if number in duplicates:
                        continue
                    nums[replace] = number
                    replace += 1
                    duplicates.add(number)
                
                return replace
        

        4.7.1547 - 2023-07-13 18:52:44 +0300 MSK

        Remove Element

        Code

        class Solution:
            # create replace index
            # iterate over nums:
            # - if the current number is equal to val, continue
            # - set nums[replace] to that number, increase the index
        
            def removeElement(self, nums: List[int], val: int) -> int:
                replace = 0
                for i, number in enumerate(nums):
                    if number == val:
                        continue
                    nums[replace] = number
                    replace += 1
                
                return replace
        

        4.7.1548 - 2023-07-13 18:46:43 +0300 MSK

        Remove Element

        Code

        class Solution:
            # create two indexes, current and replace
            # create non_val_count
            # while to-be-replaced has not reached the end:
            # - if the current number is a regular number, move the current index, 
            #   increase non_val_count
            # - if the replace index is equal or less than the current, move it and continue
            # - if the replace number is a non-regular number, move the replace index and continue
            # - if the current number is a non-regular, replace it with the replace number, 
            #   replace the replace number with val, move both indexes
            # return the current index + 1
        
            def removeElement(self, nums: List[int], val: int) -> int:
                current, replace, val_count, length = 0, 0, 0, len(nums)
                non_val_count = 0
                
                while replace < length and current < length:
                    current_number, replace_number = nums[current], nums[replace]
                    
                    if current_number != val:
                        current += 1
                        non_val_count += 1
                        continue
        
                    if replace <= current:
                        replace = current + 1
                        continue
        
                    if replace_number == val:
                        replace += 1
                        continue
        
                    nums[current], nums[replace] = replace_number, val
                    replace += 1
                    current += 1
                    non_val_count += 1
                    
                return non_val_count
        

        4.7.1549 - 2023-07-12 20:34:00 +0300 MSK

        Merge Sorted Array

        Code

        class Solution:
            # have three indexes: nums1 (end of array 1), nums2 (from the end), 
            # and current (nums1 from the end) 
            # if nums2 number is bigger or equal than nums1 number, put the number at the current index,
            # move both indexes
            # if nums1 number is smaller than nums2 number, put the number at the current index, 
            # move both indexes  
            def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
                """
                Do not return anything, modify nums1 in-place instead.
                """
        
                nums1_i, nums2_i = m - 1, n - 1
                for i in range(m + n - 1, -1, -1):
                    nums1_number  = nums1[nums1_i] if nums1_i >= 0 else nums2[0] - 1
                    nums2_number = nums2[nums2_i] if nums2_i >= 0 else nums1[0] - 1
                    if nums1_number >= nums2_number:
                        nums1[i] = nums1_number
                        nums1_i -= 1
                        continue
                    
                    nums1[i] = nums2_number
                    nums2_i -= 1
        

        4.7.1550 - 2023-07-11 17:42:28 +0300 MSK

        Valid Palindrome

        Code

        class Solution:
            def isPalindrome(self, s: str) -> bool:
                length = len(s)
        
                # if the sring has only one symbol and it is alphanumeric, it is a palyndrom
                if s.isalnum() and length == 1:
                    return True 
                
                i, j = 0, length - 1
                # iterate from the start and from the end using two indexes:
                # - if one the symbols is not alphanumeric, move the corresponding index
                # - if symbols are alphanumeric and not equal, return False
                # - move indexes
                while i < j:
                    symbol_start, symbol_end = s[i].lower(), s[j].lower()
                    if not symbol_start.isalnum():
                        i += 1
                        continue
                    if not symbol_end.isalnum():
                        j -= 1
                        continue
                    
                    if symbol_start != symbol_end:
                        return False
                    
                    i += 1
                    j -= 1
                
                return True
        

        4.7.1551 - 2023-07-11 17:40:20 +0300 MSK

        Valid Palindrome

        Code

        class Solution:
            def isPalindrome(self, s: str) -> bool:
                length = len(s)
        
                # if the sring has only one symbol and it is alphanumeric, it is a palyndrom
                if s.isalnum() and length == 1:
                    return True 
                
                i, j = 0, length - 1
                # iterate from start and from end:
            # - if the symbol is not alphanumeric, skip
            # - if the symbol is alphanumeric, compare
            # - if indexes are equal or reversed, return
                while i < j:
                    symbol_start, symbol_end = s[i].lower(), s[j].lower()
                    if not symbol_start.isalnum():
                        i += 1
                        continue
                    if not symbol_end.isalnum():
                        j -= 1
                        continue
                    
                    if symbol_start != symbol_end:
                        return False
                    
                    i += 1
                    j -= 1
                
                return True
        

        4.7.1552 - 2023-07-10 15:59:08 +0300 MSK

        Find the Index of the First Occurrence in a String

        Code

        class Solution:
            # check edge cases:
            # - if length of the needle is less than the length of the haystack: -1
            # - if strings are equal: 0
            # - if length of the needle is equal to the length of the haystack, but 
            #   strings are not equal: -1
            # iterate over haystack and needle cheking if a substring starting with the current symbol
            # is equal to the needle
            def strStr(self, haystack: str, needle: str) -> int:
                length_needle, length_haystack = len(needle), len(haystack)
                last_needle_index = length_needle - 1
        
                if length_needle > length_haystack:
                    return -1
                
                if haystack == needle:
                    return 0
        
                if length_needle == length_haystack:
                    return -1
                
                if needle == haystack:
                    return 0
        
                for i, _ in enumerate(haystack):
                    current_needle = haystack[i:i+length_needle]
                    if current_needle == needle:
                        return i
                return -1
        

        4.7.1553 - 2023-07-10 15:57:30 +0300 MSK

        Find the Index of the First Occurrence in a String

        Code

        class Solution:
            # check edge cases:
            # - if length of the needle is less than the length of the haystack: -1
            # - if strings are equal: 0
            # - if length of the needle is equal to the length of the haystack, but 
            #   strings are not equal: -1
            # iterate over haystack and needle cheking if a symbol from haystack 
            #   corresponds to the symbol in needle
            def strStr(self, haystack: str, needle: str) -> int:
                length_needle, length_haystack = len(needle), len(haystack)
                last_needle_index = length_needle - 1
        
                if length_needle > length_haystack:
                    return -1
                
                if haystack == needle:
                    return 0
        
                if length_needle == length_haystack:
                    return -1
                
                if needle == haystack:
                    return 0
        
                j = length_needle
                for i, _ in enumerate(haystack):
                    current_needle = haystack[i:j]
                    if current_needle == needle:
                        return i
                    j += 1
                
                return -1
        

        4.7.1554 - 2023-07-10 15:49:18 +0300 MSK

        Find the Index of the First Occurrence in a String

        Code

        class Solution:
            # check edge cases:
            # - if length of the needle is less than the length of the haystack: -1
            # - if strings are equal: 0
            # - if length of the needle is equal to the length of the haystack, but 
            #   strings are not equal: -1
            # iterate over haystack and needle cheking if a symbol from haystack 
            #   corresponds to the symbol in needle
            def strStr(self, haystack: str, needle: str) -> int:
                length_needle, length_haystack = len(needle), len(haystack)
                last_needle_index = length_needle - 1
        
                if length_needle > length_haystack:
                    return -1
                
                if haystack == needle:
                    return 0
        
                if length_needle == length_haystack:
                    return -1
                
                if needle == haystack:
                    return 0
        
                i, j = 0, length_needle
                while j <= len(haystack):
                    current_needle = haystack[i:j]
                    if current_needle == needle:
                        return i
        
                    i += 1
                    j += 1
                
                return -1
        

        4.7.1555 - 2023-07-08 18:57:18 +0300 MSK

        Length of Last Word

        Code

        class Solution:
            # we need to iterate over the string searching for words
            # add a whitespace to the end to avoid the situation when the last symbol is non-whitespace 
            # possible combinations:
            # 1. a whitespace after a symbol: end of the word
            # 2. a whitespace after a whitespace: ignore
            # 3. a symbol after a symbol: ignore
            def lengthOfLastWord(self, s: str) -> int:
                s += " "
                result, word_length = 0, 0
        
                for i, symbol in enumerate(s):
                    if symbol != " ":
                        word_length += 1
                        continue
                    
                    if word_length > 0:
                        result = word_length
                        word_length = 0
                
                return result
        

        4.7.1556 - 2023-07-08 18:48:01 +0300 MSK

        Length of Last Word

        Code

        class Solution:
            # we need to iterate over the string searching for words
            # possible combinations:
            # 1. a whitespace after a symbol: end of the word
            # 2. a whitespace after a whitespace: ignore
            # 3. a symbol after a symbol, but it's the last symbol: end of the last word
            # 4. a symbol after a symbol: ignore
            def lengthOfLastWord(self, s: str) -> int:
                length = len(s)
                if length == 1:
                    return 1
        
                word_start, word_end, in_word = 0, 0, False
        
                for i, symbol in enumerate(s):
                    is_whitespace = symbol == " "
                    is_last = i == length - 1
                    
                    if is_whitespace and in_word:
                        in_word = False
                        word_end = i - 1
                        continue
                    
                    if is_whitespace and not in_word:
                        continue
        
                    if not is_whitespace and in_word and is_last:
                        word_end = i
                        continue
        
                    if not is_whitespace and not in_word and is_last:
                        word_end = i
                        word_start = i
                        continue
        
                    if not is_whitespace and in_word:
                        continue
        
                    if not is_whitespace and not in_word:
                        word_start = i
                        in_word = True
                        continue
                    
                return word_end - word_start + 1
        

        4.7.1557 - 2023-07-08 18:25:39 +0300 MSK

        Length of Last Word

        Code

        class Solution:
            def lengthOfLastWord(self, s: str) -> int:
                return len(s.split()[-1])
        

        4.7.1558 - 2023-07-06 20:44:21 +0300 MSK

        Add Two Numbers

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        class Solution:
            # create the result pointer that points towards one of the lists
            # create the result root pointer that will point towards the root of the result list
            # 1. start infinite loop
            # 2. if result is false - break, we reached the end
            # 3. get values from non-empty pointers
            # 4. add values together, store the carry in a variable
            # 5. store the value in the result pointer
            # 6. move the result pointer to the next node, if there is no next node, use a node from
            #    another list
            # 7. move list pointers
            # 8. if we have a carry left, add a node to the result list
            def addTwoNumbers(self, l1: Optional[ListNode], 
                                    l2: Optional[ListNode]) -> Optional[ListNode]:
                carry = 0
                result, result_root = l1, l1
        
                while True:
                    if not l1 and not l2:
                        break
                    
                    number_1 = l1.val if l1 else 0
                    number_2 = l2.val if l2 else 0
                    result_val = number_1 + number_2 + carry
                    if result_val > 9:
                        carry, result_val = 1, result_val - 10
                    else:
                        carry = 0
                    
                    result.val = result_val
                    if not result.next and l2:
                        l1 = None
                        result.next = l2.next
        
                    if result.next:
                        result = result.next
                    if l1:
                        l1 = l1.next
                    if l2:
                        l2 = l2.next
        
                if carry:
                    result.next = ListNode(carry)
        
                return result_root
        

        4.7.1559 - 2023-07-06 15:43:40 +0300 MSK

        Roman to Integer

        Code

        class Solution:
            def romanToInt(self, input_numbers: str) -> int:
                result = 0
                previous = None
                values = {
                    "I": 1,
                    "V": 5,
                    "X": 10,
                    "L": 50,
                    "C": 100,
                    "D": 500,
                    "M": 1000,
                }
                subtractions = set(["IV", "IX", "XL", "XC", "CD", "CM"])
        
                for number in input_numbers:
                    if f"{previous}{number}" in subtractions:
                        result = result - values[previous] * 2 + values[number]
                    else:
                        result += values[number]
                    previous = number
                
                return result
                    
        

        4.7.1560 - 2023-05-24 13:25:03 +0300 MSK

        Remove Element

        Code

        class Solution:
            def removeElement(self, nums: List[int], val: int) -> int:
                length = len(nums)
        
                if not length: 
                    return 0
        
                first = nums[0]
                if length == 1 and first == val:
                    nums.pop()
                    return 0
                if length == 1 and first != val:
                    return 1
                
                not_equal_index = -1 if first == val else 0
                for i, number in enumerate(nums[1:], 1):
                    if number == val:
                        continue
        
                    not_equal_index += 1
                    nums[not_equal_index] = number
        
                return not_equal_index + 1
                    
        

        4.7.1561 - 2023-05-24 13:11:40 +0300 MSK

        Remove Duplicates from Sorted Array

        Code

        class Solution:
            def removeDuplicates(self, nums: List[int]) -> int:
                length = len(nums)
                if length == 1:
                    return 1
                
                unique_count = 1
                last_unique_index = 0
                for i, number in enumerate(nums[1:], 1):
                    last_unique = nums[last_unique_index]
                    if number == last_unique:
                        continue
                    
                    unique_count += 1
                    last_unique_index += 1
                    nums[last_unique_index] = number
        
                nums = nums[:last_unique_index+1]
        
                return unique_count
        

        4.7.1562 - 2023-05-24 12:54:30 +0300 MSK

        Merge Two Sorted Lists

        Code

        # Definition for singly-linked list.
        # class ListNode:
        #     def __init__(self, val=0, next=None):
        #         self.val = val
        #         self.next = next
        
        class Solution:
            def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
                result = ListNode()
                current = result
                while list1 and list2:               
                    if list1.val < list2.val:
                        current.next = list1
                        list1, current = list1.next, list1
                        continue
        
                    current.next = list2
                    list2, current = list2.next, list2
                        
                if list1 or list2:
                    current.next = list1 if list1 else list2
                    
                return result.next
        

        4.7.1563 - 2023-05-24 12:13:29 +0300 MSK

        Valid Parentheses

        Code

        class Solution:
            def isValid(self, s: str) -> bool:
                brackets = []
        
                symbols = {
                    "{": "}",
                    "(": ")",
                    "[": "]"
                }
        
                open = symbols.keys()
                closed = symbols.values()
        
                for bracket in s:
                    if bracket in open:
                        brackets.append(bracket)
                        continue
        
                    if not brackets:
                        return False
        
                    last_bracket = brackets[-1]
                    if last_bracket in closed: 
                        return False
        
                    correct_closing_bracket = symbols[last_bracket]
                    if bracket != correct_closing_bracket:
                        return False
                    
                    brackets.pop()
        
                return not len(brackets)
        

        4.7.1564 - 2023-05-24 11:52:15 +0300 MSK

        Palindrome Number

        Code

        class Solution:
            def isPalindrome(self, x: int) -> bool:
                if x < 0:
                    return False
                
                if x < 10:
                    return True
                
                number = []
        
                while True:
                    remainder = x % 10
                    x = int(x / 10)
                    number.append(remainder)
                    if not x:
                        break
                    
                
                number.reverse()
                print(number)
                length = len(number)
                half_index = int(length / 2)
        
                for i, digit in enumerate(number):
                    last_digit = number[length - i - 1]
        
                    if digit != last_digit:
                        return False
                    
                    if i != half_index:
                        continue
                    
                    return True
        

        4.7.1565 - 2023-05-24 11:37:01 +0300 MSK

        Longest Common Prefix

        Code

        class Solution:
            def longestCommonPrefix(self, strs: List[str]) -> str:
                answer = []
                strings = sorted(strs)
                first = strings[0]
                last = strings[-1]
                min_length = min(len(first), len(last))
                for i in range(min_length):
                    first_symbol = first[i]
                    last_symbol = last[i]
                    if first_symbol == last_symbol:
                        answer.append(first_symbol)
                        continue
                    
                    return "".join(answer)
        
                return "".join(answer)
        
        
                
        

        4.7.1566 - 2023-05-24 11:26:20 +0300 MSK

        Roman to Integer

        Code

        class Solution:
            def romanToInt(self, s: str) -> int:
                result = 0
                skip = False
        
                values = {
                    "I": 1,
                    "V": 5,
                    "X": 10,
                    "L": 50,
                    "C": 100,
                    "D": 500,
                    "M": 1000
                }
                special_cases = {
                    "I": ["V", "X"],
                    "X": ["L", "C"],
                    "C": ["D", "M"]
                }
        
                for i, symbol in enumerate(s):
                    if skip:
                        skip = False
                        continue
        
                    next = None
                    if i < (len(s) - 1):
                        next = s[i+1]
        
                    if next in special_cases.get(symbol, []):
                        skip = True
                        result += values[next] - values[symbol]
                        continue
                    
                    result += values[symbol]
        
                return result
                    
        

        4.7.1567 - 2023-05-24 11:15:01 +0300 MSK

        Roman to Integer

        Code

        class Solution:
            def romanToInt(self, s: str) -> int:
                result = 0
                skip = False
                for i, symbol in enumerate(s):
                    if skip:
                        skip = False
                        continue
        
                    next = ""
                    if i < len(s) - 1:
                        next = s[i+1]
                    
                    if symbol == "I" and next == "V":
                        result += 4
                        skip = True
                        continue
        
                    if symbol == "I" and next == "X":
                        result += 9
                        skip = True
                        continue
                    
                    if symbol == "I":
                        result += 1
                        continue
        
                    if symbol == "X" and next == "L":
                        result += 40
                        skip = True
                        continue
        
                    if symbol == "X" and next == "C":
                        result += 90
                        skip = True
                        continue
                    
                    if symbol == "X":
                        result += 10
                        continue
        
                    if symbol == "C" and next == "D":
                        result += 400
                        skip = True
                        continue
                    
                    if symbol == "C" and next == "M":
                        result += 900
                        skip = True
                        continue
                    
                    if symbol == "C":
                        result += 100
                        continue
                    
                    if symbol == "V":
                        result += 5
                        continue
                    
                    if symbol == "D":
                        result += 500
                        continue
                    
                    if symbol == "M":
                        result += 1000
                        continue
                    
                    if symbol == "L":
                        result += 50
                        continue
                    
                    raise Exception(f"unexpected situation: {symbol}, {next}")
        
                return result
                    
        

        4.7.1568 - 2023-05-23 12:36:30 +0300 MSK

        Two Sum

        Code

        class Solution:
            def twoSum(self, nums: List[int], target: int) -> List[int]:
                indexes = {}
                for i, number in enumerate(nums):
                    diff = target - number
                    if diff in indexes: 
                        return [indexes[diff], i]
                    indexes[number] = i
        

        4.7.1569 - 2023-05-23 12:30:44 +0300 MSK

        Two Sum

        Code

        class Solution:
            def twoSum(self, nums: List[int], target: int) -> List[int]:
                for i, number in enumerate(nums):
                    for j, number_inner in enumerate(nums[i+1:]):
                        if number + number_inner == target:
                            return [i, i+j+1]
        

        4.7.1570 - 2022-05-17 07:59:02 +0300 MSK

        Find a Corresponding Node of a Binary Tree in a Clone of That Tree

        Code

        class Solution {
        TreeNode ans;
        
        public void inorder(TreeNode c,TreeNode target) {
        if (c != null) {
        inorder(c.left, target);
        if (c.val == target.val) {
        ans = c;
        }
        inorder(c.right, target);
        }
        }
        
        public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target)
        {
        inorder(cloned,target);
        return ans;
        }
        }
        

        4.7.1571 - 2022-05-15 18:44:33 +0300 MSK

        Deepest Leaves Sum

        Code

        /**
         * Definition for a binary tree node.
         * public class TreeNode {
         *     int val;
         *     TreeNode left;
         *     TreeNode right;
         *     TreeNode() {}
         *     TreeNode(int val) { this.val = val; }
         *     TreeNode(int val, TreeNode left, TreeNode right) {
         *         this.val = val;
         *         this.left = left;
         *         this.right = right;
         *     }
         * }
         */
        class Solution {
            public int deepestLeavesSum(TreeNode root) {
                MaxDepthInfo maxDepthInfo = new MaxDepthInfo(0 ,0);
                sumAtLevel(root, 0, maxDepthInfo);
                return maxDepthInfo.getSumAtMaxDepth();
            }
        
            public void sumAtLevel(TreeNode root, int currentDepth, MaxDepthInfo maxDepthInfo) {
                if (root == null) return;
        
                if (currentDepth > maxDepthInfo.getMaxDepth()) {
                    maxDepthInfo.setMaxDepth(currentDepth);
                    maxDepthInfo.setSumAtMaxDepth(root.val);
                }
        
                else if (currentDepth == maxDepthInfo.getMaxDepth())
                    maxDepthInfo.setSumAtMaxDepth(maxDepthInfo.getSumAtMaxDepth() + root.val);
        
                sumAtLevel(root.left, currentDepth + 1, maxDepthInfo);
                sumAtLevel(root.right, currentDepth + 1, maxDepthInfo);
            }
        
            public static class MaxDepthInfo {
                private int maxDepth;
                private int sumAtMaxDepth;
        
                public MaxDepthInfo(int maxDepth, int sumAtMaxDepth) {
                    this.maxDepth = maxDepth;
                    this.sumAtMaxDepth = sumAtMaxDepth;
                }
        
                public int getMaxDepth() { return maxDepth;}
        
                public void setMaxDepth(int maxDepth) { this.maxDepth = maxDepth;}
        
                public int getSumAtMaxDepth() { return sumAtMaxDepth;}
        
                public void setSumAtMaxDepth(int sumAtMaxDepth) { this.sumAtMaxDepth = sumAtMaxDepth;}
            }
        }
        

        4.7.1572 - 2022-05-14 15:28:36 +0300 MSK

        Network Delay Time

        Code

        class Solution {
           private final Map<Integer, List<Node>> connected = new HashMap<>();
        
            public int networkDelayTime(int[][] times, int n, int k) {
                for (int[] time : times) {
                    connected.putIfAbsent(time[0], new ArrayList<>());
                    connected.get(time[0]).add(new Node(time[2], time[1]));
                }
                connected.forEach((source, nodes) -> nodes.sort(Comparator.comparing(Node::travelTime)));
                int[] receivedTime = new int[n + 1]; Arrays.fill(receivedTime, 1, receivedTime.length, Integer.MAX_VALUE);
                dfs(receivedTime, 0, k);
                
                int max = Arrays.stream(receivedTime).max().orElseThrow(RuntimeException::new);
                return max == Integer.MAX_VALUE ? -1 : max;
            }
        
            private void dfs(int[] receivedTime, int currentTime, int currentNode) {
                if (receivedTime[currentNode] <= currentTime) return;
                receivedTime[currentNode] = currentTime;
                if (connected.containsKey(currentNode))
                    connected.get(currentNode).forEach(node -> dfs(receivedTime, currentTime + node.travelTime(), node.destination()));
            }
        
            public record Node(int travelTime, int destination) {}
        }
        

        4.7.1573 - 2022-05-13 07:19:10 +0300 MSK

        Letter Combinations of a Phone Number

        Code

        class Solution {
            public List<String> letterCombinations(String digits) {
                if(digits.length() == 0){
                    List<String> result = new ArrayList<>();
                    return result;
                }
                List<String> res = combine(digits); 
                return res;
            }
            
            public List<String> combine(String digit){
                if(digit.length() == 0 ){
                    List<String> result = new ArrayList<>();
                    result.add("");
                    return result;
                }
                
                String[] codes = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
                
                char c = digit.charAt(0);
                
                String  digits_left = digit.substring(1);
                
                List<String> res = combine(digits_left);
                
                List<String> result = new ArrayList<>();
                
                String code_for_current_digit = codes[c-'0'];
                
                for(int i=0;i<code_for_current_digit.length();i++){
                    char code_char = code_for_current_digit.charAt(i);
                    
                    if(!res.isEmpty()){
                        for(String s : res){
                            result.add(code_char + s);
                        }    
                    }
                    else{
                        res.add(String.valueOf(code_char));
                    }
                    
                }
                
                
                return result;
            }
        }
        

        4.7.1574 - 2022-05-13 07:17:45 +0300 MSK

        Populating Next Right Pointers in Each Node II

        Code

        class Solution {
            public Node connect(Node root) {
                Node leftMost = root;
                while (leftMost != null) {
                    Node cur = leftMost;
                    leftMost = null;
                    Node pre = null;
                    while (cur != null) {
                        if (leftMost == null) {
                            leftMost = cur.left == null ? cur.right: cur.left;
                        }
                        if (pre != null) {
                            pre.next = cur.left == null ? cur.right : cur.left;
                        }
                        if (cur.left != null && cur.right != null) {
                            cur.left.next = cur.right;
                        }
                        pre = cur.right == null ? (cur.left == null ? pre : cur.left) : cur.right;
                        cur = cur.next;
                    }
                }
                return root;
            }
        }
        

        4.7.1575 - 2022-05-12 18:05:33 +0300 MSK

        Permutations II

        Code

        class Solution {
        public List<List<Integer>> permuteUnique(int[] nums) {
                List<List<Integer>> permutations = new ArrayList<>();
                Arrays.sort(nums);
                backtracking(permutations, new ArrayList<>(), nums, new boolean[nums.length]);
                return permutations;
            }
        
            private void backtracking(List<List<Integer>> permutations, List<Integer> current, int[] nums, boolean[] used) {
                if (current.size() == nums.length)
                    permutations.add(new ArrayList<>(current));
                else {
                    for (int i = 0; i < nums.length; i++) {
                        if (used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])) continue;
                        current.add(nums[i]);
                        used[i] = true;
                        backtracking(permutations, current, nums, used);
                        used[i] = false;
                        current.remove(current.size() - 1);
                    }
                }
            }
        }
        

        4.7.1576 - 2022-05-11 18:03:06 +0300 MSK

        Count Sorted Vowel Strings

        Code

        class Solution {
            public int countVowelStrings(int n) {
                int a,e,i,o,u;
                a = e = i = o = u = 1;
                
                for(int t = 1; t < n; t++){
                    
                    a = a + e + i + o + u;
                    e = e + i + o + u;
                    i = i + o + u;
                    o = o + u;
                    u = u;
                }
                return a + e + i + o + u;
            }
        }
        

        4.7.1577 - 2022-05-08 17:27:21 +0300 MSK

        Flatten Nested List Iterator

        Code

        public class NestedIterator implements Iterator<Integer> {
        
            private List<Integer> integerList = new ArrayList<>();
            private int index = 0;
            public NestedIterator(List<NestedInteger> nestedList) {
                for (NestedInteger nestedInteger : nestedList) {
                    flatten(nestedInteger);
                }
            }
            
            private void flatten(NestedInteger nested) {
                if (nested.isInteger()) 
                    integerList.add(nested.getInteger());
                else 
                    for (NestedInteger nestedFromList : nested.getList()) {
                        flatten(nestedFromList);
                }
            }
        
            @Override
            public boolean hasNext() {
                return index < integerList.size();
            }
        
            @Override
            public Integer next() {
                return integerList.get(index++);
            }
        }
        

        4.7.1578 - 2022-05-07 13:44:16 +0300 MSK

        132 Pattern

        Code

        
        func find132pattern(numbers []int) bool {
        	length := len(numbers)
        	if length < 3 {
        		// if the array doesn't have at least three numbers, it cannot have
        		// '123' pattern
        		return false
        	}
        	list, third_element := list.List{}, math.MinInt
        	for index := length - 1; index >= 0; index-- {
        		current := numbers[index]
        		if current < third_element {
        			return true
        		}
        		for list.Len() != 0 && list.Front().Value.(int) < current {
        			third_element = list.Front().Value.(int)
        			list.Remove(list.Front())
        		}
        		list.PushFront(current)
        	}
        	return false
        }
        

        4.7.1579 - 2022-05-07 13:05:13 +0300 MSK

        Backspace String Compare

        Code

        
        func backspaceCompare(string_1 string, string_2 string) bool {
        	length_1, length_2 := len(string_1), len(string_2)
        	list_1, list_2, length_biggest := list.List{}, list.List{}, length_1
        	if length_2 > length_1 {
        		length_biggest = length_2
        	}
        	for index := 0; index < length_biggest; index++ {
        		if index < length_1 {
        			backspace_action(&list_1, string_1[index])
        		}
        		if index < length_2 {
        			backspace_action(&list_2, string_2[index])
        		}
        	}
        	// lists are not equal, there is no need to check
        	if list_1.Len() != list_2.Len() {
        		return false
        	}
        	// checking elements after all deletions
        	element_1, element_2 := list_1.Back(), list_2.Back()
        	for element_1 != nil {
        		if element_1.Value != element_2.Value {
        			// elements are not equal -> strings are not equal
        			return false
        		}
        		element_1, element_2 = element_1.Next(), element_2.Next()
        	}
        	// checked all elements, strings are equal
        	return true
        }
        
        func backspace_action(list *list.List, character byte) {
        	switch {
        	case character == '#' && list.Len() != 0:
        		// delete last character
        		list.Remove(list.Front())
        		fallthrough
        	case character == '#' && list.Len() == 0:
        		// just return if the list is empty
        		return
        	}
        	list.PushFront(character)
        }
        

        4.7.1580 - 2022-05-06 20:02:58 +0300 MSK

        Backspace String Compare

        Code

        class Solution {
            public boolean backspaceCompare(String S, String T) {
                return build(S).equals(build(T));
            }
        
            public String build(String S) {
                Stack<Character> ans = new Stack();
                for (char c: S.toCharArray()) {
                    if (c != '#')
                        ans.push(c);
                    else if (!ans.empty())
                        ans.pop();
                }
                return String.valueOf(ans);
            }
        }
        

        4.7.1581 - 2022-05-06 19:50:38 +0300 MSK

        Remove Duplicates from Sorted Array

        Code

        func removeDuplicates(numbers []int) int {
        	// ensure there are at least two numbers
        	length := len(numbers)
        	if length == 1 {
        		return 1
        	}
        	index_non_duplicate := 1
        	for index := 1; index < length; index++ {
        		current, previous := numbers[index], numbers[index-1]
        		if current == previous {
        			// it is a duplicate - ignore it
        			continue
        		}
        		// it is not a duplicate -> place it and move the index
        		numbers[index_non_duplicate] = current
        		index_non_duplicate++
        	}
        	return index_non_duplicate
        }
        

        4.7.1582 - 2022-05-06 19:25:00 +0300 MSK

        Remove All Adjacent Duplicates in String II

        Code

        class Solution {
            public String removeDuplicates(String s, int k) {
                Stack<int []> Master = new Stack<>();
                
                for(char ch : s.toCharArray()){
                    if(!Master.isEmpty() && Master.peek()[0] == ch){
                        Master.peek()[1]++;
                    }
                    else Master.push(new int[]{ch, 1});
                    if(Master.peek()[1] == k) Master.pop();
                }
                StringBuilder sb = new StringBuilder();
                while(!Master.isEmpty()){
                    int top[] = Master.pop();
                    while(top[1] --> 0)
                        sb.append((char)top[0]);
                }
                return sb.reverse().toString();
            }
        }
        

        4.7.1583 - 2022-05-05 18:39:53 +0300 MSK

        Sign of the Product of an Array

        Code

        
        func arraySign(numbers []int) int {
        	negative_count := 0
        	for _, number := range numbers {
        		switch {
        		// the number is 0 -> product of all numbers is definitely zero
        		case number == 0:
        			return 0
        			// the number is negative -> add to count
        		case number < 0:
        			negative_count++
        		}
        	}
        	// even amount of negative numbers -> result is positive
        	if negative_count&1 == 0 {
        		return 1
        	}
        	// uneven amount of negative numbers -> result is negative
        	return -1
        }
        

        4.7.1584 - 2022-05-05 18:26:39 +0300 MSK

        Find Smallest Letter Greater Than Target

        Code

        
        
        func nextGreatestLetter(letters []byte, target byte) byte {
        	length := len(letters)
        	left, right := 0, length-1
        	for right >= left {
        		index := left + (right-left)/2
        		character := letters[index]
        		// the character is bigger, we found at least one result
        		// smaller characters are to the left -> discard right
        		if character > target {
        			right = index - 1
        			continue
        		}
        		// character is either equal or smaller -> there is no results to the
        		// left -> discard left
        		left = index + 1
        	}
        	return letters[left%length]
        }
        

        4.7.1585 - 2022-05-05 15:37:11 +0300 MSK

        Sqrt(x)

        Code

        
        func mySqrt(number int) int {
        	left, right := 0, number
        	for right >= left {
        		current := left + (right-left)/2
        		square_current := current * current
        		square_next := (current + 1) * (current + 1)
        		switch {
        		case square_current <= number && square_next > number:
        			// found the target
        			return current
        		case square_current > number:
        			// target is to the left -> discard right
        			right = current - 1
        		case square_current < number:
        			// target is to the right -> discard left
        			left = current + 1
        		}
        	}
        	return -1
        }
        

        4.7.1586 - 2022-05-05 15:10:54 +0300 MSK

        Reverse Words in a String III

        Code

        func reverseWords(_string string) string {
        	index_word_start, length, result := 0, len(_string), []rune(_string)
        	for index, character := range result {
        		// ignore normal characters
        		if character != ' ' {
        			continue
        		}
        		// word ended -> reverse characters from the start of the word to the
        		//end of it
        		reverse_word(result, length, index_word_start, index)
        		index_word_start = index + 1
        	}
        	reverse_word(result, length, index_word_start, length)
        	return string(result)
        }
        
        func reverse_word(_string []rune, length int, start int, end int) {
        	//fmt.Println("reversing", string(_string), start, "->", end)
        	length_word := end - start
        	for index := start; index < start+length_word/2; index++ {
        		index_last := end - (index - start) - 1
        		current, last := _string[index], _string[index_last]
        		_string[index], _string[index_last] = last, current
        	}
        	//fmt.Println("result", string(_string), start, "->", end)
        }
        

        4.7.1587 - 2022-05-05 13:50:33 +0300 MSK

        Reverse String

        Code

        func reverseString(characters []byte) {
        	length := len(characters)
        	for index := 0; index < length/2; index++ {
        		index_last := length - index -1 
        		current, last := characters[index], characters[index_last]
        		characters[index_last] = current
        		characters[index] = last
        	}
        }
        

        4.7.1588 - 2022-05-05 13:43:47 +0300 MSK

        Two Sum II - Input Array Is Sorted

        Code

        func twoSum(numbers []int, target int) []int {
        	numbers_len := len(numbers)
        	for index, number := range numbers {
        		for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
        			if numbers[index_inner]+number == target {
        				return []int{index + 1, index_inner + 1}
        			}
        		}
        	}
        	return []int{}
        }
        

        4.7.1589 - 2022-05-05 13:39:30 +0300 MSK

        Move Zeroes

        Code

        func moveZeroes(numbers []int) {
        	index_zero := -1
        	// sliding window algorithm
        	for index, number := range numbers {
        		// if index_zero is not set, then the first zero is index_zero
        		if index_zero == -1 && number == 0 {
        			index_zero = index
        		}
        		// there is no need to move numbers if there were no zeros before
        		// there is no need to move zeros
        		if index_zero == -1 || number == 0 {
        			continue
        		}
        		// after some zeros we encounter a non-zero number
        		// moving that number to the beginning of zeros
        		numbers[index_zero] = number
        		// current number becomes zero
        		numbers[index] = 0
        		// moving the index
        		index_zero++
        	}
        }
        

        4.7.1590 - 2022-05-05 13:39:06 +0300 MSK

        Move Zeroes

        Code

        func moveZeroes(nums []int)  {
            count:=0
            for i:=0; i<len(nums);i++{
                if nums[i] == 0{
                    count++
                }else{
                    nums[i-count]=nums[i]
                }
            }
            for count>0{
                nums[len(nums)-count] = 0
                count--
            }
            
            
        }
        

        4.7.1591 - 2022-05-05 13:38:25 +0300 MSK

        Move Zeroes

        Code

        func moveZeroes(nums []int)  {
            	if len(nums) < 2 {
        		return
        	}
        
        	for z, p := 0, 1; p < len(nums) && z < len(nums); {
        		if nums[z] == 0 && nums[p] != 0 {
        			if p > z {
        				nums[z], nums[p] = nums[p], nums[z]
        				z++
        			}
        			p = z+1
        		} else {
        			if nums[z] != 0 {
        				z++
        			}
        			if nums[p] == 0 {
        				p++
        			}
        		}
        	}
        
        }
        

        4.7.1592 - 2022-05-05 13:32:58 +0300 MSK

        Move Zeroes

        Code

        
        func moveZeroes(numbers []int) {
        	index_zero := -1
        	// sliding window algorithm
        	for index, number := range numbers {
        		// if index_zero is not set, then the first zero is index_zero
        		if index_zero == -1 && number == 0 {
        			index_zero = index
        		}
        		// there is no need to move numbers if there were no zeros before
        		// there is no need to move zeros
        		if index_zero == -1 || number == 0 {
        			continue
        		}
        		// after some zeros we encounter a non-zero number
        		// moving that number to the beginning of zeros
        		numbers[index_zero] = number
        		// current number becomes zero
        		numbers[index] = 0
        		// moving the index
        		index_zero++
        	}
        }
        

        4.7.1593 - 2022-05-05 13:14:51 +0300 MSK

        Move Zeroes

        Code

        
        func moveZeroes(numbers []int) {
        	// ensure there are at least two numbers
        	length := len(numbers)
        	if length == 1 {
        		return
        	}
        	result, index_result := make([]int, length), 0
        	for _, number := range numbers {
        		if number == 0 {
        			continue
        		}
        		result[index_result] = number
        		index_result++
        	}
        	copy(numbers, result)
        }
        

        4.7.1594 - 2022-05-05 07:01:33 +0300 MSK

        Implement Stack using Queues

        Code

        
        type MyStack struct{ queue *list.List }
        
        func Constructor() MyStack           { return MyStack{&list.List{}} }
        func (this *MyStack) Push(value int) { this.queue.PushFront(value) }
        func (this *MyStack) Top() int       { return this.queue.Front().Value.(int) }
        func (this *MyStack) Empty() bool    { return this.queue.Len() == 0 }
        func (this *MyStack) Pop() int {
        	return this.queue.Remove(this.queue.Front()).(int)
        }
        

        4.7.1595 - 2022-05-04 13:13:54 +0300 MSK

        Best Time to Buy and Sell Stock

        Code

        
        func maxProfit(prices []int) int {
        	profit, index_buy := 0, 0
        	for index, price := range prices {
        		if prices[index_buy] > price {
        			index_buy = index
        		}
        		new_profit := price - prices[index_buy]
        		if new_profit > profit {
        			profit = new_profit
        		}
        	}
        	return profit
        }
        

        4.7.1596 - 2022-05-04 12:54:11 +0300 MSK

        Intersection of Two Arrays II

        Code

        
        func intersect(numbers_1 []int, numbers_2 []int) (result []int) {
        	// 0 <= nums1[i], nums2[i] <= 1000
        	count := make([]int, 1001)
        	// counting how many times a number occured in the first array
        	for _, number := range numbers_1 {
        		count[number]++
        	}
        	for _, number := range numbers_2 {
        		// the number did not occur in the first array
        		// -> ignoring it
        		if count[number] <= 0 {
        			continue
        		}
        		count[number]--
        		result = append(result, number)
        	}
        	return
        }
        

        4.7.1597 - 2022-05-04 12:36:38 +0300 MSK

        Intersection of Two Arrays II

        Code

        
        func intersect(numbers_1 []int, numbers_2 []int) []int {
        	length_1, length_2 := len(numbers_1), len(numbers_2)
        	length_biggest, result := length_1, make([]int, length_1+length_2)
        	if length_2 > length_1 {
        		length_biggest = length_2
        	}
        	occurences := make(map[int][]int, length_biggest)
        
        	for index := 0; index < length_biggest; index++ {
        		if index < length_1 {
        			add_to_occurences(numbers_1[index], 0, occurences)
        		}
        		if index < length_2 {
        			add_to_occurences(numbers_2[index], 1, occurences)
        		}
        	}
        	index := 0
        	for number, occurence := range occurences {
        		repeat := occurence[0]
        		if occurence[1] < repeat {
        			repeat = occurence[1]
        		}
        		for ; repeat > 0; repeat-- {
        			result[index] = number
        			index++
        		}
        	}
            return result[0 : index]
        }
        func add_to_occurences(number int, index int, occurences map[int][]int) {
        	if _, occured := occurences[number]; !occured {
        		occurences[number] = make([]int, 2)
        	}
        	occurences[number][index]++
        }
        

        4.7.1598 - 2022-05-04 08:33:36 +0300 MSK

        Merge Sorted Array

        Code

        
        func merge(array1 []int, length1 int, array2 []int, length2 int) {
        	if length2 == 0 {
        		return
        	}
        	if length1 == 0 {
        		for index, number := range array2 {
        			array1[index] = number
        		}
        		return
        	}
        	index1, index2, array1Copy := 0, 0, make([]int, length1)
        	copy(array1Copy, array1)
        	for index := 0; index < length1+length2; index++ {
        		fmt.Println(index, index1, index2, array1, array2)
        		for index2 < length2 && (index1 >= length1 || array2[index2] <= array1Copy[index1]) {
        			array1[index] = array2[index2]
        			index2++
        			index++
        		}
        		if index1 >= length1 {
        			continue
        		}
        		array1[index] = array1Copy[index1]
        		index1++
        	}
        }
        

        4.7.1599 - 2022-05-04 08:32:16 +0300 MSK

        Two Sum

        Code

        
        func twoSum(numbers []int, target int) []int {
        	numbers_len := len(numbers)
        	for index, number := range numbers {
        		for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
        			if numbers[index_inner]+number == target {
        				return []int{index, index_inner}
        			}
        		}
        	}
        	return []int{}
        }
        

        4.7.1600 - 2022-05-04 08:30:20 +0300 MSK

        Find the Distance Value Between Two Arrays

        Code

        
        func findTheDistanceValue(array_1 []int, array_2 []int, target int) int {
        	// sorting it to use binary search
        	sort.Ints(array_2)
        	length_2, count := len(array_2), 0
        	for _, current_1 := range array_1 {
        		left, right, add_to_count := 0, length_2-1, true
        		for right >= left {
        			index := left + (right-left)/2
        			current_2 := array_2[index]
        			if abs(current_1, current_2) <= target {
        				// current_1 is inside |arr1[i]-arr2[j]| <= d
        				// -> ignore it
        				add_to_count = false
        				break
        			}
        			switch {
        			case current_2 > current_1:
        				// current_2 is bigger than current_1
        				// -> all numbers to the right are bigger
        				// -> discard right, add to count
        				right = index - 1
        			case current_2 < current_1:
        				// current_2 is smaller than current_1
        				// -> all numbers to the left are smaller
        				// -> discard left, add to count
        				left = index + 1
        			}
        		}
        		if add_to_count {
        			count++
        		}
        	}
        	return count
        }
        
        func abs(number_1 int, number_2 int) int {
        	difference := number_1 - number_2
        	if difference < 0 {
        		return difference * -1
        	}
        	return difference
        }
        

        4.7.1601 - 2022-05-04 07:34:24 +0300 MSK

        Valid Perfect Square

        Code

        
        func isPerfectSquare(number int) bool {
        	left, right := 1, number
        	for right >= left {
        		current := left + (right-left)/2
        		square := current * current
        		switch {
        		case square == number:
        			// found the target
        			return true
        		case square > number:
        			// square is bigger -> root is to the left -> discard right
        			right = current - 1
        		case square < number:
        			// square is smaller -> root is to the right -> discard left
        			left = current + 1
        		}
        	}
        	return false
        }
        

        4.7.1602 - 2022-05-04 07:03:31 +0300 MSK

        Find Nearest Point That Has the Same X or Y Coordinate

        Code

        func nearestValidPoint(x int, y int, points [][]int) int {
        	point_target, smallest_distance, smallest_index := []int{x, y}, math.MaxInt, -1
        	for index, point := range points {
        		// ignore the point if it is not valid
        		if !valid(point_target, point) {
        			continue
        		}
        		distance := distance(point_target, point)
        		// ignore the point if its Manhattan distance is bigger
        		if distance >= smallest_distance {
        			continue
        		}
        		// the distance is smaller, update the index and the distance
        		smallest_index, smallest_distance = index, distance
        	}
        	// there are no valid points
        	if smallest_index == -1 {
        		return -1
        	}
        	return smallest_index
        }
        
        func valid(point_target []int, point []int) bool {
        	switch {
        	case point_target[0] == point[0]:
        		fallthrough
        	case point_target[1] == point[1]:
        		return true
        	default:
        		return false
        	}
        }
        
        func distance(point_target []int, point []int) int {
        	return abs(point_target[0]-point[0]) + abs(point_target[1]-point[1])
        }
        
        func abs(number int) int {
        	if number < 0 {
        		return number * -1
        	}
        	return number
        }
        

        4.7.1603 - 2022-05-04 06:39:29 +0300 MSK

        Largest Perimeter Triangle

        Code

        
        func largestPerimeter(numbers []int) int {
        	sort.Ints(numbers)
        	for index := len(numbers) - 1; index > 1; index-- {
        		current, sum_previous := numbers[index], numbers[index-1]+numbers[index-2]
        		if current >= sum_previous {
        			continue
        		}
        		return current + sum_previous
        	}
        	return 0
        }
        

        4.7.1604 - 2022-05-04 06:26:24 +0300 MSK

        Max Number of K-Sum Pairs

        Code

        
        func maxOperations(numbers []int, sum int) int {
        	count, previous := 0, make(map[int]int, len(numbers))
        	for _, current := range numbers {
        		target := sum - current
        		target_unmatched, target_occured := previous[target]
        		// if the current number has not occured before, then it is not in the map
        		// -> it needs to be initialized
        		if _, current_occured := previous[current]; !current_occured {
        			previous[current] = 0
        		}
        		// number of duplicates of the current number has increased
        		previous[current]++
        		switch {
        		case target_occured && target_unmatched == 0:
        			// the target has occured before but there are no unmatched duplicates
        			fallthrough
        		case !target_occured:
        			// in order to get the sum we need the target, but it has not appeared yet
        			continue
        		case target_occured && target_unmatched > 0:
        			// the target has appeared before and there are some unmached duplicates left
        			// -> removing the current number and the target from possible matches
        			previous[current]--
        			previous[target]--
        			count++
        		}
        	}
        	return count
        }
        

        4.7.1605 - 2022-05-04 05:57:55 +0300 MSK

        Subtract the Product and Sum of Digits of an Integer

        Code

        func subtractProductAndSum(number int) int {
        	fist_digit := number % 10
        	factorial, sum := fist_digit, fist_digit
        	number /= 10
        	for number > 0 {
        		digit := number % 10
        		factorial *= digit
        		sum += digit
        		number /= 10
        	}
        	return factorial - sum
        }
        

        4.7.1606 - 2022-05-04 05:49:11 +0300 MSK

        Number of 1 Bits

        Code

        
        func hammingWeight(number uint32) (result int) {
        	for number > 0 {
        		if number&1 != 0 {
        			result++
        		}
        		number >>= 1
        	}
        	return
        }
        

        4.7.1607 - 2022-05-03 18:34:04 +0300 MSK

        Peak Index in a Mountain Array

        Code

        
        func peakIndexInMountainArray(array []int) int {
        	left, right := 0, len(array)-1
        	for right > left {
        		// overflow protection
        		index := left + (right-left)/2
        		// next element is bigger -> top is to the right -> discard left
        		if array[index+1] > array[index] {
        			left = index + 1
        			continue
        		}
        		// next element is equal or smaller -> discard right
        		// 'index' could be the answer, so it should not be discarded
        		right = index
        	}
        	return right
        }
        

        4.7.1608 - 2022-05-03 17:44:29 +0300 MSK

        Search Insert Position

        Code

        func searchInsert(numbers []int, target int) int {
        	// checking edge cases
        	length := len(numbers)
        	if numbers[0] == target {
        		return 0
        	} else if numbers[length-1] == target {
        		return length - 1
        	}
        	left, right, index, was_bigger := 0, length-1, 0, false
        	for right >= left {
        		// overflow protection
        		index = left + (right-left)/2
        		number := numbers[index]
        		//fmt.Println("index", index, "left", left, "right", right)
        		switch {
        		case number == target:
        			// found the target
        			return index
        		case number > target:
        			// the number is bigger -> the target is to the left -> discard right
        			right = index - 1
        			was_bigger = true
        		case number < target:
        			// the number is smaller -> the target is to the right -> discard left
        			left = index + 1
        			was_bigger = false
        		}
        	}
        	// the target is not in the array
        
        	// the last number was bigger -> target should be to the left
        	if was_bigger {
        		return index
        	}
        	// the last number was smaller -> target should be to the right
        	return index + 1
        }
        

        4.7.1609 - 2022-05-03 17:39:58 +0300 MSK

        Rotate Array

        Code

        
        func rotate(numbers []int, steps int) {
        	length := len(numbers)
        	// removing unnecessary steps
        	if steps >= length {
        		steps %= length
        	}
        	// checking edge cases
        	if length == 1 || steps == 0 {
        		return
        	}
        	results := make([]int, length)
        	for index, number := range numbers {
        		results[(index+steps)%length] = number
        	}
        	copy(numbers, results)
        }
        

        4.7.1610 - 2022-05-03 15:28:52 +0300 MSK

        Rotate Array

        Code

        
        func rotate(numbers []int, steps int) {
        	length := len(numbers)
        	// removing unnecessary steps
        	if steps >= length {
        		steps %= length
        	}
        	// checking edge cases
        	if length == 1 || steps == 0 {
        		return
        	}
        	remainder, rotation_start := make([]int, steps), length-steps
        	// copy everything that needs to be shifted to another array
        	copy(remainder, numbers[rotation_start:])
        	// move everything to the right
        	copy(numbers[steps:], numbers[0:rotation_start])
        	// move shifted elements to the beginning
        	copy(numbers[0:steps], remainder)
        }
        

        4.7.1611 - 2022-05-03 15:08:53 +0300 MSK

        Squares of a Sorted Array

        Code

        func sortedSquares(numbers []int) []int {
        	length := len(numbers)
        	if length == 0 || length == 1 {
        		return square(numbers, false)
        	}
        	negativesIndex := -1
        	for index, number := range numbers {
        		if number >= 0 {
        			negativesIndex = index
        			break
        		}
        	}
        	if negativesIndex == 0 || negativesIndex == -1 {
        		return square(numbers, negativesIndex == -1)
        	}
        //	fmt.Println("negativesIndex", negativesIndex)
        	result, resultIndex, negativesIndex := make([]int, length), 0, negativesIndex-1
        	for positivesIndex := negativesIndex + 1; resultIndex < length; positivesIndex++ {
        		positiveOverflow := positivesIndex >= length
        		for {
        			if negativesIndex < 0 || resultIndex >= length {
        				break
        			}
        			if !positiveOverflow && numbers[negativesIndex]*-1 > numbers[positivesIndex] {
        				break
        			}
        			result[resultIndex] = numbers[negativesIndex]
        			resultIndex++
        //			fmt.Println("negative", negativesIndex, resultIndex, numbers[negativesIndex], result, numbers)
        			negativesIndex--
        		}
        		if resultIndex < length && !positiveOverflow {
        //			fmt.Println("positivesIndex", positivesIndex, resultIndex, numbers[positivesIndex], result, numbers)
        			result[resultIndex] = numbers[positivesIndex]
        			resultIndex++
        		}
        	}
        	return square(result, false)
        }
        
        func square(array []int, reverse bool) []int {
        	if reverse {
        		length := len(array)
        		reversed := make([]int, length)
        		for index := length - 1; index >= 0; index-- {
        			reversed[length-index-1] = array[index] * array[index]
        		}
        		return reversed
        	} else {
        		for index, number := range array {
        			array[index] = number * number
        		}
        		return array
        	}
        }
        

        4.7.1612 - 2022-05-03 15:05:02 +0300 MSK

        Squares of a Sorted Array

        Code

        
        func sortedSquares(numbers []int) []int {
        	length := len(numbers)
        	switch length {
        	case 0:
        		return numbers
        	case 1:
        		return []int{numbers[0] * numbers[0]}
        	}
        	index_left, index_right := 0, length-1
        	results := make([]int, length)
        	for index := index_right; index_left <= index_right; index-- {
        		left_square := numbers[index_left] * numbers[index_left]
        		right_square := numbers[index_right] * numbers[index_right]
        		if right_square > left_square {
        			results[index] = right_square
        			index_right--
        			continue
        		}
        		results[index] = left_square
        		index_left++
        	}
        	return results
        }
        

        4.7.1613 - 2022-05-03 13:17:41 +0300 MSK

        Shortest Unsorted Continuous Subarray

        Code

        
        func findUnsortedSubarray(numbers []int) int {
        	length := len(numbers)
        	// checking edge cases
        	if length == 1 {
        		return 0
        	}
        	result := make([]int, length)
        	// initializing to MaxInt because zeros will impact future sorting
        	for index := range result {
        		result[index] = math.MaxInt
        	}
        	index_sort_start, index_sort_end := length, length
        	result[0] = numbers[0]
        	for index := 1; index < length; index++ {
        //		fmt.Println(result, index_sort_start, "->", index_sort_end)
        		// current is not sorted -> from numbers
        		// previous is sorted -> from result
        		current, previous := numbers[index], result[index-1]
        		// just push the current number in the result array because if it is
        		// bigger
        		if current >= previous {
        			result[index] = current
        			continue
        		}
        		// current number is not sorted -> moving the end index
        		index_sort_end = index + 1
        		// current < previous -> find the number bigger than the current
        		//
        		// the current number is smaller than the starting number of the unsorted subarray
        		// (or the starting index is not set)
        		// -> start index is invalid, finding new start index in numbers
        		if index_sort_start == length || current < result[index_sort_start] {
        			// insert the number in the correct place and move index_sort_start
        			// to the correct place
        			if index_sort_start == length {
        				// index_sort_start is not set -> setting to the last sorted number
        				index_sort_start = index - 1
        			}
        			index_sort_start = insert_smaller(result, current, index_sort_start, 0)
        			continue
        		}
        		// the current number is bigger than the starting number of the unsorted
        		// subarray, so it should be placed inside of it
        		insert_smaller(result, current, index, index_sort_start)
        		// set start index (if not already set)
        		if index < index_sort_start {
        			index_sort_start = index - 1
        		}
        	}
        //	fmt.Println(result, index_sort_start, "->", index_sort_end)
        	// return length of the sorted subarray
        	return index_sort_end - index_sort_start
        }
        
        func insert_smaller(numbers []int, target int, index_start int, index_end int) int {
        	index_result := index_end
        	for index := index_start; index >= index_end; index-- {
        		if target >= numbers[index] {
        			// target is bigger -> it should be placed after this index
        			index_result = index + 1
        			break
        		}
        	}
        //	fmt.Println("index for", target, "-", index_result)
        	// target should be placed after index_result, so move everything after
        	// it to the right and insert the current number
        	// if index_result is the last item, then just push it
        	copy(numbers[index_result+1:], numbers[index_result:])
        	numbers[index_result] = target
        	return index_result
        }
        

        4.7.1614 - 2022-05-03 13:17:21 +0300 MSK

        Shortest Unsorted Continuous Subarray

        Code

        
        func findUnsortedSubarray(numbers []int) int {
        	length := len(numbers)
        	// checking edge cases
        	if length == 1 {
        		return 0
        	}
        	result := make([]int, length)
        	// initializing to MaxInt because zeros will impact future sorting
        	for index := range result {
        		result[index] = math.MaxInt
        	}
        	index_sort_start, index_sort_end := length, length
        	result[0] = numbers[0]
        	for index := 1; index < length; index++ {
        //		fmt.Println(result, index_sort_start, "->", index_sort_end)
        		// current is not sorted -> from numbers
        		// previous is sorted -> from result
        		current, previous := numbers[index], result[index-1]
        		// just push the current number in the result array because if it is
        		// bigger
        		if current >= previous {
        			result[index] = current
        			continue
        		}
        		// current number is not sorted -> moving the end index
        		index_sort_end = index + 1
        		// current < previous -> find the number bigger than the current
        		//
        		// the current number is smaller than the starting number of the unsorted subarray
        		// (or the starting index is not set)
        		// -> start index is invalid, finding new start index in numbers
        		if index_sort_start == length || current < result[index_sort_start] {
        			// insert the number in the correct place and move index_sort_start
        			// to the correct place
        			if index_sort_start == length {
        				// index_sort_start is not set -> setting to the last sorted number
        				index_sort_start = index - 1
        			}
        			index_sort_start = insert_smaller(result, current, index_sort_start, 0)
        			continue
        		}
        		// the current number is bigger than the starting number of the unsorted
        		// subarray, so it should be placed inside of it
        		insert_smaller(result, current, index, index_sort_start)
        		// set start index (if not already set)
        		if index < index_sort_start {
        			index_sort_start = index - 1
        		}
        	}
        //	fmt.Println(result, index_sort_start, "->", index_sort_end)
        	// return length of the sorted subarray
        	return index_sort_end - index_sort_start
        }
        
        func insert_smaller(numbers []int, target int, index_start int, index_end int) int {
        	index_result := index_end
        	for index := index_start; index >= index_end; index-- {
        		if target >= numbers[index] {
        			// target is bigger -> it should be placed after this index
        			index_result = index + 1
        			break
        		}
        	}
        //	fmt.Println("index for", target, "-", index_result)
        	// target should be placed after index_result, so move everything after
        	// it to the right and insert the current number
        	// if index_result is the last item, then just push it
        	copy(numbers[index_result+1:], numbers[index_result:])
        	numbers[index_result] = target
        	return index_result
        }
        

        4.7.1615 - 2022-05-02 19:07:40 +0300 MSK

        Sort Array By Parity

        Code

        
        func sortArrayByParity(numbers []int) []int {
        	length := len(numbers)
        	if length == 1 {
        		return numbers
        	}
        	results, index_even, index_odd := make([]int, length), 0, length-1
        	for _, number := range numbers {
        		if (number & 1) == 0 {
        			// number is even -> place it from the beginning
        			results[index_even] = number
        			index_even++
        		} else {
        			// number is odd -> place it from the end
        			results[index_odd] = number
        			index_odd--
        		}
        	}
        	return results
        }
        

        4.7.1616 - 2022-05-02 18:49:07 +0300 MSK

        Search Insert Position

        Code

        func searchInsert(numbers []int, target int) int {
        	// checking edge cases
        	length := len(numbers)
        	if numbers[0] == target {
        		return 0
        	} else if numbers[length-1] == target {
        		return length - 1
        	}
        	left, right, index, was_bigger := 0, length-1, 0, false
        	for right >= left {
        		// overflow protection
        		index = left + (right-left)/2
        		number := numbers[index]
        		//fmt.Println("index", index, "left", left, "right", right)
        		switch {
        		case number == target:
        			// found the target
        			return index
        		case number > target:
        			// the number is bigger -> the target is to the left -> discard right
        			right = index - 1
        			was_bigger = true
        		case number < target:
        			// the number is smaller -> the target is to the right -> discard left
        			left = index + 1
        			was_bigger = false
        		}
        	}
        	// the target is not in the array
        
        	// the last number was bigger -> target should be to the left
        	if was_bigger {
        		return index
        	}
        	// the last number was smaller -> target should be to the right
        	return index + 1
        }
        

        4.7.1617 - 2022-05-02 18:02:36 +0300 MSK

        First Bad Version

        Code

        
        func firstBadVersion(n int) int {
        	// checking edge cases
        	if isBadVersion(1) {
        		return 1
        	}
        	left, right, bad_version := 1, n, math.MaxInt
        	for right >= left {
        		// overflow protection
        		version := left + (right-left)/2
        		switch isBadVersion(version) {
        		case false:
        			// it is good -> versions to the left are good -> discard left
        			left = version + 1
        		case true:
        			// it is bad -> the first bad version is either this one or to the left
        			// discard right
        			bad_version = version
        			right = version - 1
        		}
        	}
        	// the search space is empty
        	return bad_version
        }
        

        4.7.1618 - 2022-05-02 17:51:33 +0300 MSK

        Binary Search

        Code

        /* https://leetcode.com/problems/binary-search/
        
        Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
        
        You must write an algorithm with O(log n) runtime complexity.
        
        
        
        Example 1:
        
        Input: nums = [-1,0,3,5,9,12], target = 9
        Output: 4
        Explanation: 9 exists in nums and its index is 4
        
        Example 2:
        
        Input: nums = [-1,0,3,5,9,12], target = 2
        Output: -1
        Explanation: 2 does not exist in nums so return -1
        
        
        
        Constraints:
        
            1 <= nums.length <= 104
            -104 < nums[i], target < 104
            All the integers in nums are unique.
            nums is sorted in ascending order.
        
        */
        package main
        
        func search(numbers []int, target int) int {
        	length := len(numbers)
        	switch {
        	case numbers[0] > target:
        		// smallet number > target = there is no target in the array
        		fallthrough
        	case numbers[length-1] < target:
        		// biggest number < target = there is no target in the array
        		return -1
        	case numbers[length-1] == target:
        		// checking just in case, can save time
        		return length - 1
        	case numbers[0] == target:
        		// checking just in case, can save time
        		return 0
        	}
        
        	left, right := 0, length-1
        	for right >= left {
        		// overflow protection
        		index := left + (right-left)/2
        		number := numbers[index]
        		switch {
        		case number == target:
        			// found the target
        			return index
        		case number > target:
        			// array is in the ascending order, the number is bigger
        			// -> the target is to the left -> discard right
        			right = index - 1
        		case number < target:
        			// array is in the ascending order, the number is smaller
        			// -> the target is to the right -> discard left
        			left = index + 1
        		}
        	}
        	// search space is empty, there is no target
        	return -1
        }
        

        4.7.1619 - 2022-05-02 17:49:22 +0300 MSK

        Guess Number Higher or Lower

        Code

        
        func guessNumber(n int) int {
        	// checking edge cases
        	if guess(1) == 0 {
        		return 1
        	} else if guess(n) == 0 {
        		return n
        	}
        	left, right := 1, n
        	for right >= left {
        		// overflow protection
        		number := left + (right-left)/2
        		switch guess(number) {
        		case 0:
        			// found the target
        			return number
        		case -1:
        			// the number is bigger -> the target is to the left -> discard right
        			right = number - 1
        		case 1:
        			// the number is smaller -> the target is to the right -> discard left
        			left = number + 1
        		}
        	}
        	// ide shows an error, this return is unreachable in this issue
        	return 0
        }
        

        4.7.1620 - 2022-05-02 17:34:04 +0300 MSK

        Binary Search

        Code

        /* https://leetcode.com/problems/binary-search/
        
        Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
        
        You must write an algorithm with O(log n) runtime complexity.
        
        
        
        Example 1:
        
        Input: nums = [-1,0,3,5,9,12], target = 9
        Output: 4
        Explanation: 9 exists in nums and its index is 4
        
        Example 2:
        
        Input: nums = [-1,0,3,5,9,12], target = 2
        Output: -1
        Explanation: 2 does not exist in nums so return -1
        
        
        
        Constraints:
        
            1 <= nums.length <= 104
            -104 < nums[i], target < 104
            All the integers in nums are unique.
            nums is sorted in ascending order.
        
        */
        package main
        
        func search(numbers []int, target int) int {
        	length := len(numbers)
        	switch {
        	case numbers[0] > target:
        		// smallet number > target = there is no target in the array
        		fallthrough
        	case numbers[length-1] < target:
        		// biggest number < target = there is no target in the array
        		return -1
        	case numbers[length-1] == target:
        		// checking just in case, can save time
        		return length - 1
        	case numbers[0] == target:
        		// checking just in case, can save time
        		return 0
        	}
        
        	left, right := 0, length-1
        	for right >= left {
        		// overflow protection
        		index := left + (right-left)/2
        		number := numbers[index]
        		switch {
        		case number == target:
        			// found the target
        			return index
        		case number > target:
        			// array is in the ascending order, the number is bigger
        			// -> the target is to the left -> discard right
        			right = index - 1
        		case number < target:
        			// array is in the ascending order, the number is smaller
        			// -> the target is to the right -> discard left
        			left = index + 1
        		}
        	}
        	// search space is empty, there is no target
        	return -1
        }
        

        4.7.1621 - 2022-05-02 16:35:35 +0300 MSK

        Average Salary Excluding the Minimum and Maximum Salary

        Code

        
        func average(salary []int) float64 {
        	length := len(salary)
        	highest, lowest := math.MinInt, math.MaxInt
        	result := 0
        	for _, number := range salary {
        		result += number
        		if number > highest {
        			highest = number
        		}
        		if number < lowest {
        			lowest = number
        		}
        	}
        	return float64(result-highest-lowest) / float64(length-2)
        }
        

        4.7.1622 - 2022-05-02 16:28:49 +0300 MSK

        Count Odd Numbers in an Interval Range

        Code

        
        func countOdds(low int, high int) int {
        	low_even, high_even, half := (low&1) == 0, (high&1) == 0, (high-low)/2
        	if low_even && high_even  {
        		return half
        	}
        	return half + 1
        }
        

        4.7.1623 - 2022-05-02 14:58:45 +0300 MSK

        Maximum Subarray

        Code

        
        func maxSubArray(numbers []int) int {
        	length := len(numbers)
        	switch length {
        	case 0:
        		return 0
        	case 1:
        		return numbers[0]
        	}
        	maxCurrent, maxOverall := 0, math.MinInt
        	for _, number := range numbers {
        		maxCurrent += number
        		if maxCurrent > maxOverall {
        			maxOverall = maxCurrent
        		}
        		if maxCurrent < 0 {
        			maxCurrent = 0
        		}
        	}
        	return maxOverall
        }
        

        4.7.1624 - 2022-05-02 07:24:29 +0300 MSK

        Contains Duplicate

        Code

        
        func containsDuplicate(numbers []int) bool {
        	if len(numbers) == 0 || len(numbers) == 1 {
        		return false
        	}
        	occured := make(map[int]bool)
        	for _, number := range numbers {
        		_, isDuplicate := occured[number]
        		if isDuplicate {
        			return true
        		}
        		occured[number] = true
        	}
        	return false
        }
        

        4.7.1625 - 2022-05-01 16:23:58 +0300 MSK

        Add to Array-Form of Integer

        Code

        func addToArrayForm(number1 []int, add int) []int {
        	if add == 0 {
        		return number1
        	}
        	if len(number1) == 0 {
        		return convert(add)
        	}
        	number2 := convert(add)
        	length1, length2, carry := len(number1), len(number2), 0
        	hightest := length1
        	if length2 > length1 {
        		hightest = length2
        	}
        	result := make([]int, hightest)
        	index1, index2, indexResult := length1-1, 0, hightest-1
        	for {
        		index1Valid, index2Valid := index1 >= 0, index2 < length2
        		if !index1Valid && !index2Valid && carry==0 {
        			break
        		}
        		digit1, digit2 := 0, 0
        		if index1Valid {
        			digit1 = number1[index1]
        			index1--
        		}
        		if index2Valid {
        			digit2 = number2[index2]
        			index2++
        		}
        		digitResult := digit1 + digit2 + carry
        		if digitResult > 9 {
        			carry = 1
        			digitResult -= 10
        		} else {
        			carry = 0
        		}
        		if indexResult == -1 {
        			result = append(result, 0)
        			copy(result[1:], result[0:hightest])
                    indexResult=0
        		}
        		result[indexResult] = digitResult
        		indexResult--
        	}
        	return result
        }
        
        func convert(number int) (result []int) {
        	for {
        		if number == 0 {
        			return
        		}
        		result = append(result, number%10)
        		number /= 10
        	}
        }
        

        4.7.1626 - 2022-05-01 15:41:08 +0300 MSK

        Squares of a Sorted Array

        Code

        
        func sortedSquares(numbers []int) []int {
        	length := len(numbers)
        	if length == 0 || length == 1 {
        		return square(numbers, false)
        	}
        	negativesIndex := -1
        	for index, number := range numbers {
        		if number >= 0 {
        			negativesIndex = index
        			break
        		}
        	}
        	if negativesIndex == 0 || negativesIndex == -1 {
        		return square(numbers, negativesIndex == -1)
        	}
        	//fmt.Println("negativesIndex", negativesIndex)
        	result, resultIndex, negativesIndex := make([]int, length), 0, negativesIndex-1
        	for positivesIndex := negativesIndex + 1; resultIndex < length; positivesIndex++ {
        		positiveOverflow := positivesIndex >= length
        		for {
        			if negativesIndex < 0 || resultIndex >= length {
        				break
        			}
        			if !positiveOverflow && numbers[negativesIndex]*-1 > numbers[positivesIndex] {
        				break
        			}
        			
        			result[resultIndex] = numbers[negativesIndex]
        			resultIndex++
        			//fmt.Println("negative", negativesIndex, resultIndex, numbers[negativesIndex], result, numbers)
                    negativesIndex--
        		}
        		if resultIndex < length && !positiveOverflow {
        	//		fmt.Println("positivesIndex", positivesIndex, resultIndex, numbers[positivesIndex], result, numbers)
        			result[resultIndex] = numbers[positivesIndex]
        			resultIndex++
        		}
        	}
        	return square(result, false)
        }
        
        func square(array []int, reverse bool) []int {
        	if reverse {
        		length := len(array)
        		reversed := make([]int, length)
        		for index := length - 1; index >= 0; index-- {
        			reversed[length-index-1] = array[index] * array[index]
        		}
        		return reversed
        	} else {
        		for index, number := range array {
        			array[index] = number * number
        		}
        		return array
        	}
        }
        

        4.7.1627 - 2022-05-01 13:28:32 +0300 MSK

        Merge Sorted Array

        Code

        
        func merge(array1 []int, length1 int, array2 []int, length2 int) {
        	if length2 == 0 {
        		return
        	} 
            if length1 == 0 {
        		for index, number := range array2 {
        			array1[index] = number
        		}
        		return
        	}
        	index1, index2, array1Copy := 0, 0, make([]int, length1)
        	copy(array1Copy, array1)
        	for index := 0; index < length1+length2; index++ {
        		//fmt.Println(index, index1, index2, array1, array2)
        		for index2 < length2 && (index1 >= length1 || array2[index2] <= array1Copy[index1]) {
        			array1[index] = array2[index2]
        			index2++
        			index++
        		}
        		if index1 >= length1 {
        			continue
        		}
        		array1[index] = array1Copy[index1]
        		index1++
        	}
        }
        

        4.7.1628 - 2022-05-01 13:12:45 +0300 MSK

        Merge Sorted Array

        Code

        
        func merge(array1 []int, length1 int, array2 []int, length2 int) {
        	index1, index2, array1Copy := 0, 0, make([]int, length1)
        	copy(array1Copy, array1)
        	for index := 0; index < length1+length2; index++ {
        		fmt.Println(index, index1, index2, array1, array2)
        		if index2 < length2 && (index1 >= length1 || array2[index2] <= array1Copy[index1]) {
        			array1[index] = array2[index2]
        			index2++
        			continue
        		}
        		array1[index] = array1Copy[index1]
        		index1++
        
        	}
        }
        

        4.7.1629 - 2022-05-01 09:06:49 +0300 MSK

        Merge Two Sorted Lists

        Code

        func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
        	// ensure both lists are valid
        	switch {
        	case list1 == nil && list2 == nil:
        		return nil
        	case list1 == nil && list2 != nil:
        		return list2
        	case list1 != nil && list2 == nil:
        		return list1
        	}
        	var root *ListNode
        	if list1.Val < list2.Val {
        		root = &ListNode{list1.Val, nil}
        		list1 = list1.Next
        	} else {
        		root = &ListNode{list2.Val, nil}
        		list2 = list2.Next
        	}
        	current := &root
        	for {
        		switch {
        		case list1 == nil && list2 == nil:
        			return root
        		case list1 != nil && list2 != nil && list1.Val <= list2.Val:
        			fallthrough
        		case list1 != nil && list2 == nil:
        			fmt.Println("1", list1.Val)
        			updateResult(&current, &list1)
        		case list1 != nil && list2 != nil && list1.Val > list2.Val:
        			fallthrough
        		case list1 == nil && list2 != nil:
        			fmt.Println("2", list2.Val)
        			updateResult(&current, &list2)
        		}
        	}
        }
        func updateResult(current ***ListNode, node **ListNode) {
        	// modify the current result node
        	(**current).Next = &ListNode{(*node).Val, nil}
        	// move the current pointer
        	*current = &(**current).Next
        	// there is no next node -> nill it
        	// there is next -> move it
        	if (*node).Next == nil {
        		*node = nil
        	} else {
        		*node = (*node).Next
        	}
        }
        

        4.7.1630 - 2022-04-30 22:06:12 +0300 MSK

        Valid Parentheses

        Code

        
        func isValid(inputString string) bool {
        	if len(inputString) == 0 || (len(inputString)&1) != 0 {
        		return false
        	}
        	occurences := []rune{}
        	ends := map[rune]rune{')': '(', '}': '{', ']': '['}
        	for _, character := range inputString {
        		length := len(occurences)
        		last_valid, is_end := ends[character]
        		if (is_end && length == 0) || (is_end && occurences[length-1] != last_valid) {
        			return false
        		}
        		if is_end {
        			occurences = occurences[0 : length-1]
        		} else {
        			occurences = append(occurences, character)
        		}
        	}
        	if len(occurences) > 0 {
        		return false
        	}
        	return true
        }
        

        4.7.1631 - 2022-04-30 20:27:04 +0300 MSK

        Find Palindrome With Fixed Length

        Code

        func kthPalindrome(queries []int, intLength int) (answer []int64) {
        	for _, query := range queries {
        		answer = append(answer, getPalindrom(query, intLength))
        	}
        	return
        }
        
        func getPalindrom(query int, length int) (result int64) {
        	is_even := (length & 1) == 0
        	power := length / 2
        	if is_even {
        		power -= 1
        	}
        	palindrome := int64(math.Pow10(power)) + int64(query) - 1
        	result = palindrome
        	if !is_even {
        		palindrome /= 10
        	}
        	for palindrome > 0 {
        		result = result*10 + palindrome%10
        		palindrome /= 10
        	}
        	if len(fmt.Sprint(result)) != length {
        		return -1
        	}
        	return
        }
        

        4.7.1632 - 2022-04-30 18:34:48 +0300 MSK

        Find Palindrome With Fixed Length

        Code

        class Solution {
            public long[] kthPalindrome(int[] queries, int intLength) {
                long[] res= new long[queries.length];
                for(int i=0;i<queries.length;i++){
                    res[i]=nthPalindrome(queries[i],intLength);
                }
                return res;
            }
            public long nthPalindrome(int nth, int kdigit)
            {
            long temp = (kdigit & 1)!=0 ? (kdigit / 2) : (kdigit/2 - 1);
            long palindrome = (long)Math.pow(10, temp);
            palindrome += nth - 1;
            long res1=palindrome;
            if ((kdigit & 1)>0)
                palindrome /= 10;
            while (palindrome>0)
            {
                res1=res1*10+(palindrome % 10);
                palindrome /= 10;
            }
            String g="";
            g+=res1;
            if(g.length()!=kdigit)
                return -1;
            return res1;
        }
        }
        

        4.7.1633 - 2022-04-30 09:12:31 +0300 MSK

        Palindrome Number

        Code

        
        func isPalindrome(number int) (result bool) {
        	if number < 0 {
        		return false
        	} else if number/10 == 0 {
        		return true
        	}
        	current := number
        	digits := []int{}
        	for {
        		if current == 0 {
        			break
        		}
        		digit := current % 10
        		current /= 10
        		digits = append(digits, digit)
        	}
        	digits_length := len(digits)
        	skip := -1
        	if digits_length%2 != 0 {
        		skip = digits_length / 2
        	}
        	for index, digit := range digits {
        		if index != skip && digit != digits[digits_length-index-1] {
        			return false
        		}
        	}
        	return true
        }
        

        4.7.1634 - 2022-04-30 08:49:48 +0300 MSK

        Two Sum IV - Input is a BST

        Code

        import "sort"
        func construct(root *TreeNode, results map[int]int) {
        	if root == nil {
        		return
        	}
        	if results[root.Val] < 2 {
        		results[root.Val] += 1
        	}
        	construct(root.Left, results)
        	construct(root.Right, results)
        }
        
        func sorted(input_map map[int]int) (results []int) {
        	for key := range input_map {
        		results = append(results, key)
        	}
        	return
        }
        
        func findTarget(root *TreeNode, target int) bool {
        	if root == nil {
        		return false
        	}
        	results := map[int]int{}
        	construct(root, results)
        	if target%2 == 0 && results[target/2] == 2 {
        		return true
        	}
        	results_sorted := sorted(results)
        	results_sorted_len := len(results_sorted)
        	sort.Ints(results_sorted)
        	for index, number := range results_sorted {
        		for index_inner := index + 1; index_inner < results_sorted_len; index_inner++ {
        			if number+results_sorted[index_inner] == target {
        				return true
        			}
        		}
        	}
        	return false
        }
        

        4.7.1635 - 2022-04-30 08:49:00 +0300 MSK

        Two Sum IV - Input is a BST

        Code

        import "sort"
        
        func construct(root *TreeNode, results map[int]bool, doubles map[int]bool) {
        	if root == nil {
        		return
        	}
        	_, exists := results[root.Val]
        	if !exists {
        		results[root.Val] = true
        	} else if _, double := doubles[root.Val]; exists && double {
        		doubles[root.Val] = true
        	}
        	construct(root.Left, results, doubles)
        	construct(root.Right, results, doubles)
        }
        
        func sorted(input_map map[int]bool) (results []int) {
        	for key := range input_map {
        		results = append(results, key)
        	}
        	return
        }
        
        func findTarget(root *TreeNode, target int) bool {
        	if root == nil {
        		return false
        	}
        	results := map[int]bool{}
        	doubles := map[int]bool{}
        	construct(root, results, doubles)
        	if _, double_exists := doubles[target/2]; target%2 == 0 && double_exists {
        		return true
        	}
        	results_sorted := sorted(results)
        	results_sorted_len := len(results_sorted)
        	sort.Ints(results_sorted)
        	for index, number := range results_sorted {
        		for index_inner := index + 1; index_inner < results_sorted_len; index_inner++ {
        			if number+results_sorted[index_inner] == target {
        				return true
        			}
        		}
        	}
        	return false
        }
        

        4.7.1636 - 2022-04-30 08:30:40 +0300 MSK

        Two Sum IV - Input is a BST

        Code

        import "sort"
        
        func construct(root *TreeNode, results map[int]int) {
        	if root == nil {
        		return
        	}
        	if results[root.Val] < 2 {
        		results[root.Val] += 1
        	}
        	construct(root.Left, results)
        	construct(root.Right, results)
        }
        
        func sorted(input_map map[int]int) (results []int) {
        	for key := range input_map {
        		results = append(results, key)
        	}
        	return
        }
        
        func findTarget(root *TreeNode, target int) bool {
        	if root == nil {
        		return false
        	}
        	results := map[int]int{}
        	construct(root, results)
        	if target%2 == 0 && results[target/2] == 2 {
        		return true
        	}
        	results_sorted := sorted(results)
        	results_sorted_len := len(results_sorted)
        	sort.Ints(results_sorted)
        	for index, number := range results_sorted {
        		for index_inner := index + 1; index_inner < results_sorted_len; index_inner++ {
        			if number+results_sorted[index_inner] == target {
        				return true
        			}
        		}
        	}
        	return false
        }
        

        4.7.1637 - 2022-04-30 07:52:06 +0300 MSK

        Two Sum IV - Input is a BST

        Code

        
        func construct(root *TreeNode, results map[int]int) {
        	if root == nil {
        		return
        	}
        	if results[root.Val] < 2 {
        		results[root.Val] += 1
        	}
        	construct(root.Left, results)
        	construct(root.Right, results)
        }
        
        func findTarget(root *TreeNode, target int) bool {
        	results := map[int]int{}
        	construct(root, results)
        	for number, count := range results {
        		if count == 2 && number*2 == target {
        			return true
        		}
        		for number_inner := range results {
        			if number_inner <= number {
        				continue
        			}
        			if number+number_inner == target {
        				return true
        			}
        		}
        	}
        	return false
        }
        

        4.7.1638 - 2022-04-30 06:41:23 +0300 MSK

        Two Sum II - Input Array Is Sorted

        Code

        func twoSum(numbers []int, target int) []int {
        	numbers_len := len(numbers)
        	for index, number := range numbers {
        		for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
        			if numbers[index_inner]+number == target {
        				return []int{index + 1, index_inner + 1}
        			}
        		}
        	}
        	return []int{}
        }
        

        4.7.1639 - 2022-04-30 06:29:16 +0300 MSK

        Two Sum

        Code

        func twoSum(numbers []int, target int) []int {
        	numbers_len := len(numbers)
        	for index, number := range numbers {
        		for index_inner := index + 1; index_inner < numbers_len; index_inner++ {
        			if numbers[index_inner]+number == target {
        				return []int{index, index_inner}
        			}
        		}
        	}
        	return []int{}
        }
        

        4.7.1640 - 2022-04-30 05:36:04 +0300 MSK

        Add Two Numbers II

        Code

        func reverse(list *ListNode) *ListNode {
        	if list == nil || list.Next == nil {
        		return list
        	}
        	result := &ListNode{list.Val, nil}
        	current := list.Next
        	for {
        		if current == nil {
        			return result
        		}
        		result = &ListNode{current.Val, result}
                current = current.Next
        	}
        }
        
        func addTwoNumbers(list_1 *ListNode, list_2 *ListNode) *ListNode {
        	current_1, current_2, result := reverse(list_1), reverse(list_2), &ListNode{}
        	var carry int
        	result_current := result
        	for {
        		var value_1, value_2 int
        		if current_1 != nil {
        			value_1 = current_1.Val
        			current_1 = current_1.Next
        		}
        		if current_2 != nil {
        			value_2 = current_2.Val
        			current_2 = current_2.Next
        		}
        		sum := value_1 + value_2 + carry
        		if sum > 9 {
        			sum -= 10
        			carry = 1
        		} else {
        			carry = 0
        		}
        		result_current.Val = sum
        		if current_1 == nil && current_2 == nil && carry == 0 {
        			result_current.Next = nil
        			return reverse(result)
        		} else if current_1 == nil && current_2 == nil && carry != 0 {
        			current_1 = &ListNode{}
        		}
        		result_current.Next = &ListNode{}
        		result_current = result_current.Next
        	}
        }
        

        4.7.1641 - 2022-04-29 22:10:38 +0300 MSK

        Add Two Numbers

        Code

        
        func addTwoNumbers(list_1 *ListNode, list_2 *ListNode) *ListNode {
        	current_1, current_2, result := list_1, list_2, &ListNode{}
        	var carry int
        	result_current := result
        	for {
        		var value_1, value_2 int
        		if current_1 != nil {
        			value_1 = current_1.Val
        			current_1 = current_1.Next
        		}
        		if current_2 != nil {
        			value_2 = current_2.Val
        			current_2 = current_2.Next
        		}
        		sum := value_1 + value_2 + carry
        		if sum > 9 {
        			sum -= 10
        			carry = 1
        		} else {
        			carry = 0
        		}
        		result_current.Val = sum
        		if current_1 == nil && current_2 == nil && carry == 0 {
        			result_current.Next = nil
        			return result
        		} else if current_1 == nil && current_2 == nil && carry != 0 {
        			current_1 = &ListNode{}
        		}
        		result_current.Next = &ListNode{}
        		result_current = result_current.Next
        	}
        }
        

        4.7.1642 - 2022-04-29 19:52:46 +0300 MSK

        Longest Common Prefix

        Code

        func longestCommonPrefix(strings []string) string {
        	switch len(strings) {
        	case 0:
        		return ""
        	case 1:
        		return strings[0]
        	}
        	result := strings[0]
        for index := 1; index < len(strings); index++ {
        		current := strings[index]
        		previous := strings[index-1]
        		current_max := len(current)
        		result_max := len(result)
        		var slice_max int
        		if result_max > current_max {
        			slice_max = current_max
        			result = result[0:slice_max]
        		} else {
        			slice_max = result_max
        		}
        		for ; slice_max >= 0; slice_max-- {
        			current_slice := current[0:slice_max]
        			if current_slice == previous[0:slice_max] {
        				result = current_slice
        				break
        			}
        			if slice_max == 0 {
        				return ""
        			}
        		}
        	}	
            return result
        }
        

        4.7.1643 - 2022-04-29 18:51:04 +0300 MSK

        Longest Common Prefix

        Code

        
        func substrings(input string) map[string]bool {
        	results := make(map[string]bool)
        	for index := range input {
        		results[input[0:index+1]] = true
        	}
        	return results
        }
        
        func string_in_maps(
        	source map[string]bool,
        	target map[string]bool,
        	results map[string]bool) {
        	for string := range source {
        		is_valid, exists_in_results := results[string]
        		_, exists_in_target := target[string]
        		switch {
        		case !exists_in_target:
        			fallthrough
        		case exists_in_target && (is_valid || !exists_in_results):
        			results[string] = exists_in_target
        		}
        	}
        }
        
        func longestCommonPrefix(strings []string) (result string) {
        	results := make(map[string]bool)
        	var previous map[string]bool
        	for index, string := range strings {
        		current := substrings(string)
        		if index == 0 {
        			previous = current
        		}
        		string_in_maps(previous, current, results)
        		string_in_maps(current, previous, results)
        		previous = current
        	}
        	for string, valid := range results {
        		if valid && len(string) > len(result) {
        			result = string
        		}
        	}
        	return
        }
        

        4.7.1644 - 2022-04-29 18:09:02 +0300 MSK

        Longest Common Prefix

        Code

        
        import "fmt"
        
        
        func substrings(input string) map[string]bool {
        	results := make(map[string]bool)
        	for index := range input {
        		results[string(input[0:index+1])] = true
        	}
        	return results
        }
        
        func string_in_maps(
        	source map[string]bool,
        	target map[string]bool,
        	results map[string]bool) {
        	for string := range source {
        		if result, exists_in_results := results[string]; exists_in_results && !result {
        			continue
        		}
        		_, exists_in_target := target[string]
        		results[string] = exists_in_target
        	}
        }
        
        func longestCommonPrefix(strings []string) (result string) {
        	results := make(map[string]bool)
        	previous := make(map[string]bool)
        	for index, string := range strings {
        		current := substrings(string)
        		if index == 0 {
        			previous = current
        		}
        		string_in_maps(current, previous, results)
        		string_in_maps(previous, current, results)
        		fmt.Println("current string", string, current, "results", results)
        		previous = current
        	}
        	for string, valid := range results {
        		if !valid || len(string) < len(result) {
        			continue
        		}
        		if len(string) == len(result) && string < result {
        			result = string
        			continue
        		}
        		result = string
        	}
        	fmt.Println("result", result)
        	return
        }
        

        4.7.1645 - 2022-04-28 09:04:20 +0300 MSK

        Roman to Integer

        Code

        func romanToInt(input string) int {
        	var result int
        	types := map[rune]int{
        		'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
        	}
        	var previous rune
        	for _, character := range input {
        		result += types[character]
        		switch {
        		case previous == 'I' && (character == 'V' || character == 'X'):
        			fallthrough
        		case previous == 'X' && (character == 'L' || character == 'C'):
        			fallthrough
        		case previous == 'C' && (character == 'D' || character == 'M'):
        			result -= types[previous] * 2
        		}
        		previous = character
        	}
        	return result
        }
        

        4.7.1646 - 2022-04-28 08:59:35 +0300 MSK

        Roman to Integer

        Code

        
        func in(character rune, targets string) bool {
        	for _, target := range targets {
        		if character == target {
        			return true
        		}
        	}
        	return false
        }
        
        func romanToInt(roman string) int {
        	type dict map[rune]int
        	var result int
        	input := []rune(roman)
        	types := dict{
        		'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
        	}
        	var previous rune
        	for _, character := range input {
        		result += types[character]
        		switch {
        		case previous == 'I' && in(character, "VX"):
        			fallthrough
        		case previous == 'X' && in(character, "LC"):
        			fallthrough
        		case previous == 'C' && in(character, "DM"):
        			result -= types[previous] * 2
        		}
        		previous = character
        	}
        	return result
        }
        

        4.7.1647 - 2022-04-28 08:59:06 +0300 MSK

        Roman to Integer

        Code

        
        func in(character rune, targets string) bool {
        	for _, target := range targets {
        		if character == target {
        			return true
        		}
        	}
        	return false
        }
        
        func romanToInt(roman string) int {
        	type dict map[rune]int
        	var result int
        	types := dict{
        		'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
        	}
        	for index, character := range roman {
        		result += types[character]
                if index < 1 {
                    continue}
                switch {
        		case roman[index-1] == 'I' && in(character, "VX"):
        			fallthrough
        		case roman[index-1] == 'X' && in(character, "LC"):
        			fallthrough
        		case roman[index-1] == 'C' && in(character, "DM"):
        			result -= types[rune(roman[index-1])] * 2
        		}
        	}
        	return result
        }
        

        4.7.1648 - 2022-04-28 08:55:16 +0300 MSK

        Roman to Integer

        Code

        
        func in(character rune, targets string) bool {
        	for _, target := range targets {
        		if character == target {
        			return true
        		}
        	}
        	return false
        }
        
        func romanToInt(roman string) int {
        	type dict map[rune]int
        	var result int
        	input := []rune(roman)
        	types := dict{
        		'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
        	}
        	var previous rune
        	for _, character := range input {
        		result += types[character]
        		switch {
        		case previous == 'I' && in(character, "VX"):
        			fallthrough
        		case previous == 'X' && in(character, "LC"):
        			fallthrough
        		case previous == 'C' && in(character, "DM"):
        			result -= types[previous] * 2
        		}
        		previous = character
        	}
        	return result
        }
        

        4.8 - Mullvad

        Device limit

        Mullvad will invalidate a key If a host connects to many vpns with it at the same time

        4.9 - Old diagrams

        Old drawio diagrams

        Interview diagram

        Abandoned project idea

        4.10 - Ping

        sendmsg: operation not permitted

        This problem can be caused by vpns with “kill-switch” enabled, so you might need to disable them.

        Disable Mullvad VPN:

        sudo systemctl disable --now mullvad-daemon
        

        4.11 - Repo

        Repository-specific information

        Setup

        .env file

        • RANCHER_ALWALDEND_COM_K3S_TOKEN: k3s token for //infra/charts/rancher.dc1.alwaldend.com
        • DNSCONTROL_CLOUDFLAREAPI_ACCOUNT_ID: Cloudflare account id for //infra/dns
        • DNSCONTROL_CLOUDFLAREAPI_API_TOKEN: Cloudflare token for //infra/dns

        Setup .bzlenv

        . "$(bazel run //tools/bzlenv)"
        

        Compile commands

        Build compile_commands.json:

        bazel run :refresh_compile_commands
        

        Build everything

        bazel build //...
        

        Test everything

        bazel test //...
        

        Export .env (bzlenv should export it automatically)

        export $(cat .env | xargs)
        

        Replace a rule with another one

        find \
          "(" -name "*.bazel" -o -name "*.bzl" -o -name ".bazelrc" -o -name "*.md" ")" \
          -type f \
          -exec sed -i 's|//bzl/rules/txt|//tools/txt|g' "{}" ";"`
        

        Parse a tar manifest

        bazel build //projects/alwaldend.com:site_source_archive && \
          cat bazel-bin/projects/alwaldend.com/site_source_archive.manifest | \
          jq -r --slurp ". | flatten | .[].dest" | \
          grep "^content"
        

        Remove a rule

        find -name "BUILD.bazel" -type f -exec sed -i '/al_readme(/,/)/d' "{}" ";"
        

        Find all public targets (ignores default_visibility)

        bazel query 'attr(visibility, "//visibility:public", //...)'
        

        4.12 - Rfc

        Some useful rfcs

        4.12.1 - Rfc2119

        Rfc2119

        Html

        Txt

        
        
        
        
        
        
        Network Working Group                                         S. Bradner
        Request for Comments: 2119                            Harvard University
        BCP: 14                                                       March 1997
        Category: Best Current Practice
        
        
                Key words for use in RFCs to Indicate Requirement Levels
        
        Status of this Memo
        
           This document specifies an Internet Best Current Practices for the
           Internet Community, and requests discussion and suggestions for
           improvements.  Distribution of this memo is unlimited.
        
        Abstract
        
           In many standards track documents several words are used to signify
           the requirements in the specification.  These words are often
           capitalized.  This document defines these words as they should be
           interpreted in IETF documents.  Authors who follow these guidelines
           should incorporate this phrase near the beginning of their document:
        
              The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL
              NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED",  "MAY", and
              "OPTIONAL" in this document are to be interpreted as described in
              RFC 2119.
        
           Note that the force of these words is modified by the requirement
           level of the document in which they are used.
        
        1. MUST   This word, or the terms "REQUIRED" or "SHALL", mean that the
           definition is an absolute requirement of the specification.
        
        2. MUST NOT   This phrase, or the phrase "SHALL NOT", mean that the
           definition is an absolute prohibition of the specification.
        
        3. SHOULD   This word, or the adjective "RECOMMENDED", mean that there
           may exist valid reasons in particular circumstances to ignore a
           particular item, but the full implications must be understood and
           carefully weighed before choosing a different course.
        
        4. SHOULD NOT   This phrase, or the phrase "NOT RECOMMENDED" mean that
           there may exist valid reasons in particular circumstances when the
           particular behavior is acceptable or even useful, but the full
           implications should be understood and the case carefully weighed
           before implementing any behavior described with this label.
        
        
        
        
        
        Bradner                  Best Current Practice                  [Page 1]
        
        RFC 2119                     RFC Key Words                    March 1997
        
        
        5. MAY   This word, or the adjective "OPTIONAL", mean that an item is
           truly optional.  One vendor may choose to include the item because a
           particular marketplace requires it or because the vendor feels that
           it enhances the product while another vendor may omit the same item.
           An implementation which does not include a particular option MUST be
           prepared to interoperate with another implementation which does
           include the option, though perhaps with reduced functionality. In the
           same vein an implementation which does include a particular option
           MUST be prepared to interoperate with another implementation which
           does not include the option (except, of course, for the feature the
           option provides.)
        
        6. Guidance in the use of these Imperatives
        
           Imperatives of the type defined in this memo must be used with care
           and sparingly.  In particular, they MUST only be used where it is
           actually required for interoperation or to limit behavior which has
           potential for causing harm (e.g., limiting retransmisssions)  For
           example, they must not be used to try to impose a particular method
           on implementors where the method is not required for
           interoperability.
        
        7. Security Considerations
        
           These terms are frequently used to specify behavior with security
           implications.  The effects on security of not implementing a MUST or
           SHOULD, or doing something the specification says MUST NOT or SHOULD
           NOT be done may be very subtle. Document authors should take the time
           to elaborate the security implications of not following
           recommendations or requirements as most implementors will not have
           had the benefit of the experience and discussion that produced the
           specification.
        
        8. Acknowledgments
        
           The definitions of these terms are an amalgam of definitions taken
           from a number of RFCs.  In addition, suggestions have been
           incorporated from a number of people including Robert Ullmann, Thomas
           Narten, Neal McBurnett, and Robert Elz.
        
        
        
        
        
        
        
        
        
        
        
        
        Bradner                  Best Current Practice                  [Page 2]
        
        RFC 2119                     RFC Key Words                    March 1997
        
        
        9. Author's Address
        
              Scott Bradner
              Harvard University
              1350 Mass. Ave.
              Cambridge, MA 02138
        
              phone - +1 617 495 3864
        
              email - sob@harvard.edu
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        Bradner                  Best Current Practice                  [Page 3]
        
        

        4.13 - Shell

        Deactivate venv in subshell

        A subshell doesn’t have the deactivate function, so you have to use a workaround:

        . .venv/bin/activate
        (
            echo "subshell, still in venv: $(which python)" && \
            . "$(dirname "$(which python)")/activate" && \
            deactivate && \
            echo "subshell, out of venv: $(which python)"
        )
        

        A subshell () is different from a subprocess

        https://unix.stackexchange.com/a/138498

        A subshell starts out as an almost identical copy of the original shell process. Under the hood, the shell calls the fork system call1, which creates a new process whose code and memory are copies2. When the subshell is created, there are very few differences between it and its parent. In particular, they have the same variables. Even the $$ special variable keeps the same value in subshells: it’s the original shell’s process ID. Similarly $PPID is the PID of the parent of the original shell.

        A few shells change a few variables in the subshell. Bash ≥4.0 sets BASHPID to the PID of the shell process, which changes in subshells. Bash, zsh and mksh arrange for $RANDOM to yield different values in the parent and in the subshell. But apart from built-in special cases like these, all variables have the same value in the subshell as in the original shell, the same export status, the same read-only status, etc. All function definitions, alias definitions, shell options and other settings are inherited as well.

        A subshell created by (…) has the same file descriptors as its creator. Some other means of creating subshells modify some file descriptors before executing user code; for example, the left-hand side of a pipe runs in a subshell3 with standard output connected to the pipe. The subshell also starts out with the same current directory, the same signal mask, etc. One of the few exceptions is that subshells do not inherit custom traps: ignored signals (trap ’’ SIGNAL) remain ignored in the subshell, but other traps (trap CODE SIGNAL) are reset to the default action4.

        A subshell is thus different from executing a script. A script is a separate program. This separate program might coincidentally be also a script which is executed by the same interpreter as the parent, but this coincidence doesn’t give the separate program any special visibility on internal data of the parent. Non-exported variables are internal data, so when the interpreter for the child shell script is executed, it doesn’t see these variables. Exported variables, i.e. environment variables, are transmitted to executed programs.

        4.14 - Todo

        Todo

        Setup proper issue tracking

        Setup API docs for python, go, lua

        Codify build restrictions

        //projects builds should not depend on //tools, etc

        Maybe wth aspects, aspect hints? Or check deps using genquery?

        Fix qt install in //tools/qt

        Fix infinitime build in //projects/infinitime

        Fix //projects/useless_qt_gui build

        Add missing code for //projects/nexus_security_plugin and //projects/ci_platform

        Setup java language server

        Setup a script that adds bazel tools to ${PATH}

        Write firefox extension for //projects/leetcode_downloader

        Write tool to sync remote repos with local FS

        Rewrite python checkers to aspects

        Add prettier checks

        4.15 - Waydroid

        Shared folder and copying files

        chmod 777 file
        sudo cp file ~/.local/share/waydroid/data/media/0/Download/
        

        Docs: https://docs.waydro.id/faq/setting-up-a-shared-folder